views:

67

answers:

3

Here's what 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);
+4  A: 
(from val in DictionaryA.Values select val.name).ToList()
Matthew Flaschen
A: 

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();
David B
That's not taking the "name" part though.
Jon Skeet
Take another look at the question. He doesn't want a list of dictionary's values. He wants a list of values of a property from each dictionary object.
Anna Lear
No problemo. Editted.
David B
+7  A: 

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();
Jon Skeet