0
class PeopleDTO
{
    string Name { get; set; }
    List<AwardDTO> Awards { get; set; }
}


class AwardDTO
{
    int AwardID {get; set; }
    string AwardName {get; set; }
}

I am trying to use LINQ to filter my People Object for anyone who has an 'AwardID' equal to 5. I've tried the following but I'm not getting it:

List<PeopleDTO> people = GetPeople();
var test = (from p in people.Where(a => a.Awards.Where(a => a.AwardID == 5)) select p).ToList();

Any suggestions?

4

4 回答 4

2
people.Where(p=>p.Awards.Any(a=>a.AwardId == 5)).ToList()
于 2013-06-15T20:45:28.080 回答
0

你只需要一点点改变:

List<PeopleDTO> people = GetPeople();
var test = (from p in people.Where(a => a.Awards.Any(a => a.AwardID == 5)) select p).ToList();
于 2013-06-15T20:45:29.263 回答
0
var test = people.Where(l => l.Awards.Any(a => a.AwardId == 5));

会做..这只是查询部分,您可能想要执行它。

于 2013-06-15T20:45:33.533 回答
0

问题是Where返回匹配的元素序列,因此结果类型是错误的。这是根本问题:

// Wrong (type error)
from p in people
  .Where(
     // Results in type error as result of Where is Enumerable, not bool.
     // The lambda signature is People => Enumerable[Award] which is
     // incompatible with People => bool required for the outer Where.
     a => a.Awards.Where(a => a.AwardID == 5)
  )
select p

// Working - but NOT ideal as it forces materialization of the
// matching award count! However, types are correct.
from p in people
  .Where(
     // Now we get a lambda: People => bool
     a => a.Awards.Where(a => a.AwardID == 5).Count() > 0
  )
select p

如其他答案所述,比Where(f).Count() > 0is更理想的解决方案。Any(f)除了更清晰之外,Any它通常也是有利的,因为它不需要首先实现序列 - 毕竟,每个源元素都可以匹配。

Where 的实际结果将是一个IEnumerable[X]IQueryable[X]取决于应用它的源。关键是 Where 单独会导致不兼容的值,从而导致 lambda 类型错误。

于 2013-06-15T20:49:37.547 回答