2011-09-15 81 views
2

我想在我的詞典中找到我的源列表的所有出現。在另一個列表中搜索整數列表C#

目前,我通過我的字典循環,並比較每個字典的值。

Dictionary<string, list<int>> refList. 
List<int> sourceList. 

foreach(KeyValuePair<string, List<int>> kvp in refDict) 
{ 
    List<int> refList = (List<int>)kvp.Value; 
    bool isMatch = (refList.Count == sourceList.Count && refList.SequenceEqual(sourceList)); 
    if (isMatch) 
    { 
    ...... 
    ...... 
    } 
} 

我想找到索引以我的我的源列表的所有occurances的字典。

+1

聽起來像一個集交集給我。也許你應該使用HashSets而不是列表? – mpen

+3

我沒有看到問題。你的代碼看起來完整。 –

+0

您的意思是字典<字符串,列表> refDict? –

回答

1

我不字典項目的理解,爲什麼你需要的位置,因爲項目的順序是不確定性的,MSDN(不是索引!):

對於枚舉的目的,在字典中的每個項目被處理作爲 表示值和其 鍵的KeyValuePair結構。項目返回的順序是未定義的。

但不管怎麼說:

準備數據:

IDictionary<string, List<int>> refDict = new Dictionary<string, List<int>> 
           { 
            {"item1", new List<int> {1, 2, 3}}, 
            {"item2", new List<int> {4, 5, 6}}, 
            {"item3", new List<int> {1, 2, 3}} 
           }; 
List<int> sourceList = new List<int> {1, 2, 3}; 

搜索索引:

var indexes = refDict.Values 
    .Select((list, index) => list.SequenceEqual(sourceList) ? index : -1) 
    .Where(x => x >= 0); 

搜索鍵:

var keys = refDict 
    .Where(item => item.Value.SequenceEqual(sourceList)) 
    .Select(item => item.Key); 
0
var list = new List<int> { 1,2,3 }; 
var dico = new Dictionary<string, List<int>>(); 

dico.Add("A", list); 
dico.Add("B", new List<int> { 2,3 }); 
dico.Add("C", new List<int> { 1,2,3 }); 

var keys = dico.Where (d => d.Value.SequenceEqual(list)).Select (d => d.Key); 

注重這西港島線返回 「A」 和 「C」!

相關問題