Is there a way to extract primitive fields from a Dictionary of objects in C#?
Here's w开发者_高级运维hat I'm trying to do:
ObjectA
{
int ID;
string name;
}
I want to convert Dictionary to List where the strings in the list are the .name values of the ObjectAs in the dictionary. Obviously I could manually iterate over the dictionary values and build the list that way, but I was hoping there'd be a simpler or faster way in C# / .NET. A LINQ solution is fine, if it's simpler and faster than/as fast as:
List<string> aNames = new List<string>();
foreach(ObjectA a in DictionaryA.Values)
aNames.Add(a.name);
Here's the non-query-expression form of Matthew's answer:
var names = DictionaryA.Values.Select(x => x.name).ToList();
(I tend not to use query expressions when I'm just doing a single select or a single where, especially if I also need to call another method such as ToList
.)
Alternatively:
var names = DictionaryA.Select(x => x.Value.name).ToList();
(from val in DictionaryA.Values select val.name).ToList()
There's plenty of ways to do this once you have a query:
IQueryable<string> query = DictionaryA.Values.Select(v => v.name);
//use the Constructor of List<T> that accepts IEnumerable<T>
List<string> aNames = new List<string>(query);
//
//or use the AddRange method for existing Lists
List<string> aNames = new List<string<();
aNames.AddRange(query);
//
//or use the Enumerable.ToList extension method
List<string> aNames = query.ToList();
精彩评论