简体   繁体   English

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

[英]Search for list of integers within another list C#

I would like to find all the occurances of my source list in my dictionary. 我想在我的词典中找到我的来源清单的所有出现。

Currently, I'm looping through my dictionary, and comparing each value of 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)
  {
     ......
     ......
  }
}

I would like to find the indexes in my dict of all the occurances of my source list. 我想在我的字典中找到所有源清单中出现的索引。

I do not understand why you need a position (not an index!) of dictionary items because order of items is non deterministic, MSDN : 我不明白为什么您需要字典项的位置(而不是索引!),因为项的顺序是不确定的, MSDN

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair structure representing a value and its key. 出于枚举目的,字典中的每个项目都被视为代表值及其键的KeyValuePair结构。 The order in which the items are returned is undefined. 返回项目的顺序是不确定的。

but anyways: 但无论如何:

Prepare data: 准备数据:

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};

Search for indexes: 搜索索引:

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

Search for keys: 搜索密钥:

var keys = refDict
    .Where(item => item.Value.SequenceEqual(sourceList))
    .Select(item => item.Key);
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);

Pay attention that this wil return "A" and "C" !!! 请注意,它将返回“ A”和“ C”!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM