Assuming I have a method which accepts an IList or similar thing as a parameter:
public void JiggleMyList(IList<string> list)...
Is there an easy way that I can pass in string members of a list of objects?
I mean, if for example, I have a list of Person objects which expose a string property called FullName, is there a quick way to stuff the FullNames开发者_运维百科 of all the Person objects into the method parameter, or do I have to create a new List and iterate through the Person objects:
List<string> fullNames = new List<string>;
foreach (Person person in people)
{
fullNames.Add(person.FullName);
}
JiggleMyList(fullNames);
I come across this all the time, and it would be nice if there was a shortcut.
Many thanks
David
If you're using .NET 3.5, then you can write this using LINQ:
JiggleMyList(people.Select(p => p.FullName).ToList());
The Select
method takes a lambda expression that is used to convert each object from the source collection to some new value and these new values are collected into IEnumerablt<T>
type. The ToList
extension method converts this to List<T>
.
Alternatively, you can write the same thing using query syntax:
JiggleMyList((from p in people select p.FullName).ToList());
Similar feature is also available in .NET 2.0 (C# 2.0) and you could use anonymous delegate instead of (more elegant) lambda expressions:
JiggleMyList(people.ConvertAll(delegate (Person p) { return p.FullName; }));
var list = people.ConvertAll(x=>x.FullName).ToList();
people.ToList().ForEach(person => fullNames.Add(person.FullName));
精彩评论