views:

48

answers:

2

I have a dictionary as described in the question. My Foo class looks like this:

class Foo {
 List<Bar> Bars {get;set;}
}

I want to run through the dictionary, and assign the KeyValuePair value to the Key's Bars property. Is that possible?

I have something like this but it's a little wonky:

List<Foo> foos = new List<Foo>();

foreach(var kvp in myDict)
{
  kvp.Key.Bars = kvp.Value;
  foos.Add(kvp.Key);
}

return foos;

EDIT: This seems a little better:

    foreach (var kvp in results.Keys)
    {
        kvp.Bars = results[kvp];
    }

    return results.Select(kvp => kvp.Key);
+3  A: 

I'm not 100% sure of what you mean, but what about this:

var foos = myDict.Select(kvp =>
           {
               kvp.Key.Bars = kvp.Value;

               return kvp.Key;
           }).ToList();
lasseespeholt
I believe that's what I'm looking for!
scottm
@scottm Cool, however, you should not that these methods also change the keys `.Bars` in your myDict.
lasseespeholt
+1  A: 

How about

List<Foo> foos = (from kvp in myDict
                  select new Foo() { Bars = kvp.Value }).ToList();

or

List<Foo> foos = (from kvp in myDict
                  let dummy = (kvp.Key.Bars = kvp.Value)
                  select kvp.Key).ToList();
Jerome
with new Foo(), I lose the other properties that are already assigned.
scottm
added an alternative, actually same as lasseespeholt's answer but in pure LINQ
Jerome