簡體   English   中英

在另一個列表C#中搜索整數列表

[英]Search for list of integers within another list 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)
  {
     ......
     ......
  }
}

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

我不明白為什么您需要字典項的位置(而不是索引!),因為項的順序是不確定的, 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);
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”!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM