LINQ具有内部可枚举查询

时间:2014-07-10 16:29:32

标签: linq

我努力想要了解LINQ。在下面的例子中,我有三次会议。 Jane Doe被分配到其中两个会议。但是我认为下面的代码应该产生两个答案,显示三个会议。有什么想法吗?

class Program
{
    static void Main(string[] args)
    {
        Person p1 = new Person() { Name = "John Doe" };
        Person p2 = new Person() { Name = "Jane Doe" };
        Person p3 = new Person() { Name = "Alan Doe" };
        Meeting m1 = new Meeting() { MeetingName = "Meeting One", People = new List<Person> { p1, p2 } };
        Meeting m2 = new Meeting() { MeetingName = "Meeting Two", People = new List<Person> { p2, p3 } };
        Meeting m3 = new Meeting() { MeetingName = "Meeting Three", People = new List<Person> { p1, p3 } };
        List<Meeting> allMeetings = new List<Meeting>{m1,m2,m3};
        //Now, find all the meetings that Jane Doe is in
        var results = allMeetings.Select(x => x.People.Select(y => y.Name == "Jane Doe").Any());
        Console.WriteLine(results.Count().ToString());
        Console.ReadLine();
    }
}
public class Meeting
{
    public string MeetingName { get; set; }
    public List<Person> People { get; set; }
}
public class Person
{
    public string Name{get;set;}
}

1 个答案:

答案 0 :(得分:5)

这是问题所在:

x.People.Select(y => y.Name == "Jane Doe").Any()

当您打算使用Select进行过滤时,您正在使用Where投影。鉴于Select从未过滤掉任何项目,您基本上会返回所有任何与会者的会议。

事实上,无论如何,你可以更简单地做到这一点,因为Any可以采取一个条件:

x.People.Any(y => y.Name == "Jane Doe")