简体   繁体   中英

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.

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 .

You can have your methods accept an IEnumerable<T> (where T is the value type). For example, public void Foo(IEnumerable<string> firstNames) { ... } . This will be valid if you're only looking to iterate over the list and not access it by index as an IList<T> would let you do.

Assuming that you're ok with this, you can simply build an Enumerator object by doing the LINQ method: myPersonsList.Select(person => person.FirstName); . Due to the nature of how an Enumerable works (deferred execution), it's more efficient than creating a new list, then iterating over it.

I feel both the answers posted above will solve your problem but better to use extension methods rather than your own method.

Example is pasted for your reference.

class Program
{
    static void Main(string[] args)
    {
        List<Person> persons = new List<Person>();
        persons.Select(c => c.FirstName).DoSomething();
    }
}

public static class StringListExtension
{
    public static int DoSomething(this IEnumerable<string> strList)
    {
        return strList.Count();
    }
}

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM