tags:

views:

66

answers:

3

Hello

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.

+5  A: 

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.

Anthony Pegram
+1  A: 

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.

gmcalab
it's `List<Person>`
baron
Try the above line and see if that works, we are casting asEnumerable here....
gmcalab
`AsEnumerable()` is unnecessary. Also `Select` will result in an `IEnumerable<bool>` not an `IEnumerable<Person>`
Ahmad Mageed
@gmcalab, to explain, you're selecting the result of `x.FirstName == "Messi"`, *not* the items in the list *where* the first name equals Messi. The result, as Ahmad pointed out, is a bool, which is why you'll get an `IEnumerable<bool>`.
Anthony Pegram
+1  A: 
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"));
James Curran