Search code examples
c#linqilist

Getting an IList<field_type> from IList<object_type>


I have an IList<Person> object. The Person class has fields, FirstName, LastName, etc.

I have a function which takes IList<string> and I want to pass in the list of FirstNames in the same order of the IList<Person> object. Is there a way to do this without building List with all of the names from the Person list?

What if I could change the function to take a different parameter (other than ILIst<Person>, the function is specific to strings, not Persons), maybe IEnumerable<string>? I'd rather use the IList<string> though.


Solution

  • Enumerable.Select will return an IEnumerable of strings (first names) for you.

    http://msdn.microsoft.com/en-us/library/bb548891.aspx

    myFunction(people.Select(o => o.FirstName))

    You could also add in the ToList() if you really want to pass in a List

    myFunction(people.Select(o => o.FirstName).ToList())

    Enumerable.Select is a method that was introduced in C# 3 as part of LINQ. Read more about LINQ here. See a brief explanation of deferred execution here.