SImplifying with LINQ - Basic Choice

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

I'm just wondering if there is a way to simplify this with LINQ.

Instead of looking at all the people, I tried using LINQ to just populate the list with "Messi" ... trying something like ...

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

Then I could just add everyone to this list without checking. But it does not work as planned.

Maybe it makes no sense to simplify this expression. But the question seemed to be only to strengthen my LINQ knowledge.

+5
source share
3 answers

You're close Almost done without knowing it.

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

IEnumerable<X>, X - , peopleList.

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

List, , .ToList().

+5

peopleList? , IEnumerable LINQ.

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

List<X> AsEnumerable() , .

+1
var selectPeople = new List<Person>(peopleList.Where(x=>x.FirstName=="Messi"));

or if you already have a list:

selectPeople.AddRange(peopleList.Where(x=>x.FirstName=="Messi"));
+1
source

All Articles