选择字典<T1, T2>使用 LINQ - Select a Dictionary<T1, T2> with LINQ

问题:

I have used the "select" keyword and extension method to return an IEnumerable<T> with LINQ, but I have a need to return a generic Dictionary<T1, T2> and can't figure it out.我已经使用“select”关键字和扩展方法通过 LINQ 返回一个IEnumerable<T> ,但是我需要返回一个通用的Dictionary<T1, T2>并且无法弄清楚。 The example I learned this from used something in a form similar to the following:我从中学到的示例使用了类似于以下形式的内容:

IEnumerable<T> coll = from x in y 
    select new SomeClass{ prop1 = value1, prop2 = value2 };

I've also done the same thing with extension methods.我也对扩展方法做了同样的事情。 I assumed that since the items in a Dictionary<T1, T2> can be iterated as KeyValuePair<T1, T2> that I could just replace "SomeClass" in the above example with " new KeyValuePair<T1, T2> { ... ", but that didn't work (Key and Value were marked as readonly, so I could not compile this code).我假设因为Dictionary<T1, T2>中的项目可以迭代为KeyValuePair<T1, T2> ,所以我可以用“ new KeyValuePair<T1, T2> { ... ”替换上面示例中的“SomeClass” ,但这不起作用(键和值被标记为只读,所以我无法编译这段代码)。

Is this possible, or do I need to do this in multiple steps?这是可能的,还是我需要分多个步骤执行此操作?

Thanks.谢谢。


解决方案:

参考一: https://en.stackoom.com/question/2aaB
参考二: https://stackoom.com/question/2aaB
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章