選擇字典<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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章