Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SImplifying with LINQ - Basic selection

Tags:

c#

list

linq

foreach (var person in peopleList.Where(person => person.FirstName == "Messi")) { selectPeople.Add(person); }

I am just wondering if there is any way to simplify this using LINQ.

Like rather than look at all the people I was trying to use LINQ to just fill a list with the "Messi"'s... was trying something like...

var selectPeople = peopleList.Select(x=>x.FirstName=="Messi");

Then I could just add everyone in that list without a check. But it doesn't quite work as planned.

Maybe there's no point simplifying that expression. But the question seemed worthwhile just to strengthen my LINQ knowledge.

like image 683
baron Avatar asked Mar 31 '10 00:03

baron


Video Answer


2 Answers

You're close. Practically done without knowing it.

var selectPeople = peopleList.Where(x=>x.FirstName == "Messi");

That will create an IEnumerable<X>, where X is whatever type that's in peopleList.

The query expression syntax would be

var selectPeople = from person in peopleList
                   where person.FirstName == "Messi"
                   select person;

And to get it in concrete List format, I believe you've also already discovered the .ToList() extension.

like image 101
Anthony Pegram Avatar answered Sep 29 '22 01:09

Anthony Pegram


What type is peopleList? I believe it must be a type of IEnumerable for the LINQ to work.

var selectPeople = peopleList.AsEnumerable().Select(x=>x.FirstName=="Messi");

Since it is a List<X> type call AsEnumerable() on the list and tack on your select and it should work.

like image 33
Gabe Avatar answered Sep 29 '22 00:09

Gabe