C# 选择一个字典<;T1、T2>;与林克

C# 选择一个字典<;T1、T2>;与林克,c#,.net,linq,generics,C#,.net,Linq,Generics,我使用了“select”关键字和扩展方法,用LINQ返回了一个IEnumerable,但我需要返回一个通用字典,但无法找到它。我从中学到的示例使用了类似于以下形式的内容: IEnumerable<T> coll = from x in y select new SomeClass{ prop1 = value1, prop2 = value2 }; IEnumerable coll=从x到y 选择新的SomeClass{prop1=value1,prop2=value2}

我使用了“select”关键字和扩展方法,用LINQ返回了一个
IEnumerable
,但我需要返回一个通用
字典,但无法找到它。我从中学到的示例使用了类似于以下形式的内容:

IEnumerable<T> coll = from x in y 
    select new SomeClass{ prop1 = value1, prop2 = value2 };
IEnumerable coll=从x到y
选择新的SomeClass{prop1=value1,prop2=value2};
我也对扩展方法做了同样的事情。我假设由于
字典中的项可以迭代为
KeyValuePair
,因此我可以用“
newkeyvaluepair{…
”替换上面示例中的“SomeClass”,但这不起作用(键和值被标记为readonly,因此我无法编译此代码)

这是可能的,还是我需要分多个步骤来完成


谢谢。

extensions方法还提供了一个扩展。它使用起来相当简单,一般的用法是为键传递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);
class-SomeObject
{
公共int ID{get;set;}
公共字符串名称{get;set;}
}
SomeObject[]对象=新的SomeObject[]
{
新建SomeObject{ID=1,Name=“Hello”},
新的SomeObject{ID=2,Name=“World”}
};
Dictionary objectDictionary=objects.ToDictionary(o=>o.ID,o=>o.Name);
然后
objectDictionary[1]
将包含值“Hello”


这是假设
SomeClass.prop1
是字典所需的
键。

更明确的选项是将集合投影到
KeyValuePair
的IEnumerable,然后将其转换为字典

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);
Dictionary=对象
.Select(x=>newkeyvaluepair(x.Id,x.Name))
.ToDictionary(x=>x.Key,x=>x.Value);

.ToDictionary(item=>item.prop1,item=>item.prop2);
以明确设置值。是否可以删除.ToDictionary(x=>x.Key,x=>x.value);并用新字典替换新的KeyValuePair?
Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);