搜索另一个列表中的整数列表C#

时间:2011-09-15 15:23:23

标签: c# list dictionary

我想在我的词典中找到我的源列表的所有出现。

目前,我正在遍历我的字典,并比较字典的每个值。

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)
  {
     ......
     ......
  }
}

我想在我的dict中找到我的源列表中所有出现的索引。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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”!!!