Dictionary <Foo, List <Bar>> How to assign a list to key properties with LINQ?

I have a dictionary as described in the question. My Foo class is as follows:

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

I want to run the dictionary and assign the KeyValuePair value to the Key Bars property. Is it possible?

I have something like this, but it is a little shaky:

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
source share
2 answers

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

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

               return kvp.Key;
           }).ToList();
+3
source

What 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();
+1
source

Source: https://habr.com/ru/post/1761609/


All Articles