开发者

Using linq, can I search a list, access a property, and return a specific instance?

I have a List开发者_如何转开发 of Building. Each Building has a List of Person. I am looking for John in the buildings.

Assuming a conventional search might look like this:

List<Building> Buildings = CreateBuildings();
foreach(Building building in Buildings)
{
    foreach(Person person in building.PersonList)
    {
         if (person.Name == "John")
         {
             return person;
         }
    }
}

Also just because we can, does it mean we should? So is this an antipattern / misuse of LINQ?


That looks like:

var query = from building in Buildings
            from person in building.PersonList
            where person.Name == "John"
            select person;

That query will find all the people with a name of "John". If you want the first such person, or null if no such person can be found, you can use:

var john = query.FirstOrDefault();

Note that using extension methods you can make this query slightly more efficient:

var query = Buildings.SelectMany(x => x.PersonList)
                     .Where(x => x.Name == "John");

Or for the "first or default" version you can do even better in one step (again, very slightly):

var john = Buildings.SelectMany(x => x.PersonList)
                    .FirstOrDefault(x => x.Name == "John");

These options will avoid using the autogenerated anonymous type that the query expression would use to pair (person, building) together.

And yes, this is a perfectly valid use for LINQ - it's exactly the kind of thing it's designed for.


Yes of course, that's one of LINQ's specialties, searching.

var buildings = CreateBuildings();
var person = (from building in buildings
              from person in building.PersonList
              where person.Name == "John"
              select person)
             .FirstOrDefault();

Or another way to write it:

var person = buildings.SelectMany(building => building.PersonList)
                      .FirstOrDefault(person => person.Name == "John");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜