views:

119

answers:

6

Let's say I have an arbitray list of A

class A
{
string K {get;set;}
string V {get;set;}
}

...
List<A> theList = ...

Is there an easy way to compose a dictionary from theList? (something like the following)

Dictionary<string, string> dict = magic(x => x.K, x => x.V, theList)

I don't want to write the following code:

var d = new Dictionary<string, string>
foreach(var blah in theList)
    d[blah.K] = blah.V
+4  A: 

If the list is an IEnumerable<A> then most definitely. You would use the ToDictionary extension method on the Enumerable class in the System.Linq namespace in .NET 3.5 and beyond like so:

Dictionary<string, string> d = theList.ToDictionary(a => a.K, a => a.V);

Which will give you a Dictionary where the key is the value in the K property, and the value is the value in the V property.

casperOne
+9  A: 

There's this: Enumerable.ToDictionary.

You use it like this:

Dictionary<string, string> dict = theList.ToDictionary(e => e.K, e => e.V);
Lasse V. Karlsen
+1: The magic even looks similar to his question :-)
Cory Charlton
Nice. I learned something new, too. But I think it should be `e => e.V`.
Joel B Fant
@Joel B Fant: No, it shouldn't be `e => e.V`. Doing that will key the dictionary on V, with the values being the instances of A.
casperOne
He means that for the second parameter, it should be a lambda (=>) instead of an equals (=). Just a typo.
Brad
Ai, yes, thanks for the edit, of course it should be the lambda operator.
Lasse V. Karlsen
A: 
Dictionary<string,string> dict = new Dictionary<string,string>();

theList.ForEach( param => dict[param.K] = param.V );

A little shorter, but still basically a for-each loop. I like the ToDictionary() solution better.

Joel B Fant
@Joel B Fant: No reason to do this since LINQ provides the ToDictionary extension method for you.
casperOne
Agreed, but I didn't know about that one until now.
Joel B Fant
+1  A: 

Enumarable.ToDictionary<TSource,TKey> is what you are looking for:

theList.ToDictionary(x => x.K, x => x.V);
Oded
Just as a point of clarification, it's `Enumerable.ToDictionary`, not `IEnumerable.ToDictionary`.
Adam Robinson
@Adam Robinson - Thanks for the correction
Oded
+1  A: 
var dict = theList.Cast<A>().ToDictionary(a => a.K, a => a.V);
Asad Butt
+1  A: 
Dictionary<string, string> dict = theList.ToDictionary( x => x.K , x=> x.V);
Amgad Fahmi