使用LINQ选择字典<T1,T2>

Ric*_*ich 161 .net c# linq generics

我已经使用"select"关键字和扩展方法返回一个IEnumerable<T>LINQ,但我需要返回一个泛型Dictionary<T1, T2>而无法弄明白.我通过使用类似于以下内容的形式学习了这个例子:

IEnumerable<T> coll = from x in y 
    select new SomeClass{ prop1 = value1, prop2 = value2 };
Run Code Online (Sandbox Code Playgroud)

我也用扩展方法做了同样的事情.我假设因为a中的项 Dictionary<T1, T2>可以迭代,KeyValuePair<T1, T2>因为我可以用""替换上面例子中的"SomeClass new KeyValuePair<T1, T2> { ...",但是这不起作用(Key和Value被标记为readonly,所以我无法编译这段代码).

这是可能的,还是我需要在多个步骤中执行此操作?

谢谢.

Qui*_*son 265

extensions方法还提供ToDictionary扩展.它使用起来相当简单,一般用法是为键传递lambda选择器并将对象作为值,但是您可以为键和值传递lambda选择器.

class SomeObject
{
    public int ID { get; set; }
    public string Name { get; set; }
}

SomeObject[] objects = new SomeObject[]
{
    new SomeObject { ID = 1, Name = "Hello" },
    new SomeObject { ID = 2, Name = "World" }
};

Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);
Run Code Online (Sandbox Code Playgroud)

然后objectDictionary[1]将包含值"Hello"


alb*_*ein 42

var dictionary = (from x in y 
                  select new SomeClass
                  {
                      prop1 = value1,
                      prop2 = value2
                  }
                  ).ToDictionary(item => item.prop1);
Run Code Online (Sandbox Code Playgroud)

这是假设这SomeClass.prop1Key字典所需的.

  • `.ToDictionary(item => item.prop1,item => item.prop2);`to explicity也设置了值. (26认同)

Ant*_*eim 29

一个集合KeyValuePair更加明确,并且执行得非常好.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);
Run Code Online (Sandbox Code Playgroud)

  • 是否可以删除 .ToDictionary(x=&gt;x.Key, x=&gt;x.Value); 并用新的字典替换新的 KeyValuePair ? (2认同)