我想在我的词典中找到我的来源清单的所有出现。

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

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


我想在我的字典中找到所有源清单中出现的索引。

最佳答案

我不明白为什么您需要词典项的位置(而不是索引!),因为项的顺序是不确定的,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);

关于c# - 在另一个列表C#中搜索整数列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7433339/

10-14 17:58
查看更多