2012-07-27 38 views
0

我有一本字典,它的類型是Dictionary<int, fooClass> fooDic和另一個字典是Dictionary<int, string> barlist和我使用這個LINQ返回結果使用.ToDictionary返回另一個字典類型

var foobarList = fooDic.Where(kvp => 
     !barlist.ContainsKey(((fooClass)kvp.Value)._fooID)) 
     .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); 

這fooDic類型的返回結果。但我需要鍵入投影輸出爲barlist(Dictionary<int, string>)類型。怎麼樣?

+1

那麼,'fooClass'不是'string'(我假設)所以你想要執行什麼類型的轉換/轉換? – 2012-07-27 07:26:38

+0

是的,你是對的fooClass是一些類..我需要輸出爲字典類型... – 2012-07-27 07:27:48

+1

那麼你會如何將fooClass轉換爲字符串? – 2012-07-27 07:28:49

回答

2

如果它是一個相當簡單的轉換,關鍵是你

var foobarList = fooDic.Where(kvp => 
    !barlist.ContainsKey(((fooClass)kvp.Value)._fooID)) 
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); 

聲明的最後一部分。如果您目前使用kvp => kvp.Value,則將其替換爲kvp => kvp.Value._foobarValue

根據OP的意見編輯爲「完整」解決方案。

+0

是的,你是對的......感謝+1爲你的想法..我應該做ToDictionary(kvp => kvp.Key,kvp => kvp.Value._foobarValue);它應該是這樣的... – 2012-07-27 07:36:48

+1

這是有道理的。 =) – 2012-07-27 07:37:18

1

假設你的Foo類看起來是這樣的:

public class Foo 
{ 
    public string SomeValue { get; set; } 
    public int SomeOtherStuff { get; set; } 
} 

創建一個新的字典:

var fooDict = new Dictionary<int, Foo>() { 
    {0, new Foo() {SomeOtherStuff=10, SomeValue="some value"} }, 
    {1, new Foo() {SomeOtherStuff=15, SomeValue="some other value"} } 
}; 

將它轉換:

Dictionary<int, string> stringDict = 
    fooDict.ToDictionary(x=> x.Key, x=> x.Value.SomeValue); //<- note x.Value.SomeValue 

stringDict現在將包含:

{0, "some value"}, {1, "some other value"} 
+0

+1 Right ...我做了同樣的J給了我這個想法:) – 2012-07-27 07:37:49

+2

如果J. Steen的答案設法幫助你解決你的問題,你應該upvote並接受他的答案。 :) – 2012-07-27 07:38:27

相關問題