代码之家  ›  专栏  ›  技术社区  ›  Thorin Oakenshield

如何在C中使用LINQ从口述中删除条目#

  •  1
  • Thorin Oakenshield  · 技术社区  · 15 年前

    口述词就像

          dict["Key1"]="Value1"
          dict["Key2"]="Value2"
          dict["Key3"]="Value3"
          dict["Key4"]="Value2"
    

    提前谢谢

    4 回复  |  直到 15 年前
        1
  •  3
  •   digEmAll    15 年前

    这是我的测试解决方案:

    dict.GroupBy(x => x.Value, x => x.Key)
    .Where(x => x.Count() > 1)
    .SelectMany(x => x.Skip(1))
    .ToList().ForEach(x => dict.Remove(x))
    
        2
  •  3
  •   Community Mohan Dere    8 年前

    C#: Remove duplicate values from dictionary?

    var uniqueValues = myDict.GroupBy(pair => pair.Value)
                             .Select(group => group.First())
                             .ToDictionary(pair => pair.Key, pair => pair.Value);
    
        3
  •  1
  •   Matt Mitchell    15 年前
    var dupKeys = dict.GroupBy(innerD => innerD.Value)
                    .Where(mergedByValue => mergedByValue.Count() > 1)
                    .Select(mergedByValue => mergedByValue.OrderByDescending(m => m.Key).First().Key);
    
    dict.Where(d => dupKeys.Contains(d.Key)).ToList()
      .ForEach(d => dict.Remove(d.Key));
    

    这假设您想要 最后的 已删除重复项,其中last定义为最后一个有序字符串值。

    全部的 如果删除了重复项,请将dupkey更改为:

    var dupKeys = dict.GroupBy(innerD => innerD.Value)
                    .Where(mergedByValue => mergedByValue.Count() > 1).Dump()
                    .SelectMany(mergedByValue => mergedByValue.Select(m => m.Key));
    
        4
  •  0
  •   Incognito    15 年前

    你需要使用 Distinct .