【问题标题】:Get distinct Keys from multiple dictionaries从多个字典中获取不同的键
【发布时间】:2021-04-09 00:18:47
【问题描述】:

我有三个具有相同类型键的字典。我需要为所有三个字典获取不同的键。我该怎么做?

var rmDict = rmTrxs
  .GroupBy(x => new { x.Name, x.Pfx.Id })
  .ToDictionary(z => z.Key, z => z.ToList());

var vaDict = vaTrxs
  .GroupBy(x => new { x.Name, x.Pfx.Id })
  .ToDictionary(z => z.Key, z => z.ToList());

var smDict = smTrxs
  .GroupBy(x => new { x.Name, x.Pfx.Id })
  .ToDictionary(z => z.Key, z => z.ToList());

现在我需要从rmDictvaDictsmDict 中获取不同的键。

【问题讨论】:

标签: c# dictionary


【解决方案1】:

我理解你的意思,你可以Concat所有的键然后在Distinct的帮助下摆脱重复

 using System.Linq;

 ...

 var distinctKeys = rmDict
   .Keys
   .Concat(vaDict.Keys)
   .Concat(smDict.Keys)
   .Distinct();

对于非Linq解决方案,可以使用HashSet<T>:

 //TODO: put the right type instead of MyType
 var distinctKeys = new HashSet<MyType>(rmDict.Keys);

 distinctKeys.UnionWith(vaDict.Keys);
 distinctKeys.UnionWith(smDict.Keys);
 

【讨论】:

    【解决方案2】:
    var d1 = new Dictionary<int, string>{
        {1, "one"},
        {3, "three"},
        {5, "five"},
    };
    
    var d2 = new Dictionary<int, string>{
        {1, "one"},
        {2, "two"},
        {3, "three"},
    };
    
    var d3 = new Dictionary<int, string>{
        {2, "two"},
        {4, "four"},
        {6, "six"},
    };
    
    var dictionaries = new List<Dictionary<int, string>>{
        d1, d2, d3
    };
    var final = dictionaries.SelectMany(dict => dict)
        .ToLookup(pair => pair.Key, pair => pair.Value)
        .ToDictionary(group => group.Key, group => group.First());
        
    Console.WriteLine(final);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      相关资源
      最近更新 更多