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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With