C#将列表<model>转换为字典<enum,list <model =“”>&gt;基于模型中的枚举属性?</enum,> </model>

时间:2011-10-27 20:00:31

标签: c# linq generics lambda

不要与How can I convert List to Hashtable in C#?

混淆

我有一个模型列表,我想组织成一个以枚举为关键字的散列表,以及模型列表(具有枚举值)作为值。

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));

将列表转换为如下所示的哈希表的最简单方法是什么(原谅json):

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

当我做这样的事情时:

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

我得到了这个例外:“已经添加了具有相同密钥的项目。”

赞赏Lambda或Linq的一个衬垫!

1 个答案:

答案 0 :(得分:6)

在我看来,您可以使用Lookup

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

或者如果你真的想要Dictionary<MyEnum, List<TaskModel>>

var dictionary = models.GroupBy(o => o.Task)
                       .ToDictionary(g => g.Key, g => g.ToList());