2017-04-25 52 views
3

我有以下的解釋:的LinQ ofType在價值

public Dictionary<string,object> Items; 

現在我需要把所有的項目在字典項的價值是從一個特定的類型。 (例如「int」)

var intValues = Items.OfType<KeyValuePair<string,int>>根本不起作用。沒有LinQ在

代碼會是這樣的:

var intValues=new Dictionary<string,int>() 
foreach (var oldVal in Items) { 
    if (oldVal.Value is int) { 
    intValues.add(oldVal.Key, oldVal.Value); 
    } 
} 

(更新)我的例子應該顯示的基本理念。但如果可能的話,我會避免創建一個新的詞典作爲結果。

回答

4

可以使用is操作上Value屬性:

var intValues = Items.Where(x => x.Value is int); 

如果你想在年底的實際Dictionary<string,int>只需添加:

.ToDictionary(v=> v.Key, v=> (int)v.Value) 
2

你可以做

var result = Items.Where(x => x.Value is int) 
        .ToDictionary(x => x.Key, x => x.Value); 
7

foreach的直接翻譯將是LINQ如下:,你先篩選其中item.Valueint

var intValues = Items.Where(item => item.Value is int) 
        .ToDictionary(item => item.Key, item => (int)item.Value); 

因此,基本上,然後您可以使用ToDictionary從其中創建一個字典,將這些值轉換爲int以確保生成的字典是Dictionary<string, int>。由於我們已經過濾了非整數,所以這種類型轉換總是會成功的。

4

嘗試這樣的:

var intValue = Items 
    .Where(x => x.Value is int) // filter per Value is int 
    .ToDictionary(x => x.Key, x => (int)x.Value); // create a new dictionary converting Value to int