从IList<;词典<;字符串,对象>>;存在于IList的所有字典中的键

本文关键字:gt lt IList 字典 对象 字符串 词典 存在 | 更新日期: 2023-09-27 18:27:30

例如,在IList中,我有三个字典,它们有以下键:

字典1密钥:

aaa

aaa1

aaa2

字典2键:

aaa

aaa1

bbb3

bbb4

字典3键:

aaa

bbb3

bbb4

因此,我需要使用LINQ获得以下密钥列表:

aaa

有人能帮忙吗?

从IList<;词典<;字符串,对象>>;存在于IList的所有字典中的键

GroupBy应该足以隔离包含多个元素的密钥组:

var duplicatedKeys = myList
    .SelectMany(z => z.Keys)    // Flattens the keys to a unique IEnumerable
    .GroupBy(z => z)            // Group keys by key
    .Where(z => z.Count() > 1)  // Get groups with more than 1 occurence
    .Select(z => z.Key)         // Get the actual key
    .ToList();
var set = new HashSet<string>();
var duplicates = list
                   .SelectMany(x => x.Keys)
                   .Where(x => !set.Add(x));

以下是您需要做的:

var result = list
    .SelectMany(l => l.Keys)
    .Distinct()
    .Where(k => list.All(l => l.ContainsKey(k)))
    .ToList();

或者在@ken2k解决方案上构建(可能具有更好的性能):

var duplicatedKeys = myList
    .SelectMany(z => z.Keys)
    .GroupBy(z => z)
    .Where(z => z.Count() == myList.Count) //Number of items in group should be equal to the number of dictionaries in the list
    .Select(z => z.Key) 
    .ToList();