Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Converting a list<model> to a dictionary<enum, List<model>> based on enum property in the models?

Not to be confused with: How can I convert List to Hashtable in C#?

I have a list of Models that I want to organize into a hashtable with the enums as the key, and the list of Models (that have the enum's value) as the value.

public enum MyEnum
{
    Blue,
    Green
}

public class MyModel
{
    public MyModel(MyEnum myEnum, string foo, int bar)
    {
        this.MyEnum = myEnum;
        this.Foo = foo;
        this.Bar = bar;
    }

    public MyEnum MyEnum { get; set; }
    public string Foo { get; set; }
    public int Bar { get; set; }
}

List<MyModel> models = new List<MyModel>();

models.Add(new MyModel(MyEnum.Blue, "How", 1));
models.Add(new MyModel(MyEnum.Green, "Now", 2));
models.Add(new MyModel(MyEnum.Blue, "Brown", 3));
models.Add(new MyModel(MyEnum.Green, "Cow", 4));

What is the easiest way to convert the list into a hash table that would look like this (Forgive the json):

{ 
   Blue:
   [
      { Blue, "How", 1 },
      { Blue, "Brown", 3 }
   ],
   Green:
   [
      { Green, "Now", 2 },
      { Green, "Cow", 4 }
   ]
}

When I do something like this:

var taskTable = tasks.Cast<TaskModel>().ToDictionary(o => o.Task); (Where Task is the Enum)

I get this exception: "An item with the same key has already been added."

One liners with Lambda or Linq are appreciated!

like image 996
Levitikon Avatar asked Nov 26 '25 13:11

Levitikon


1 Answers

It looks to me like you could do with a Lookup:

var lookup = models.ToLookup(o => o.Task);

Or if you really want the Dictionary<MyEnum, List<TaskModel>>:

var dictionary = models.GroupBy(o => o.Task)
                       .ToDictionary(g => g.Key, g => g.ToList());
like image 160
Jon Skeet Avatar answered Nov 29 '25 05:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!