如何合并两个LINQ ToHashSet结果?

时间:2018-06-22 00:16:57

标签: c# linq

我有一个嵌套的字典,我想在其中找到第二个键的所有唯一值。

我这样做了:

var x=new Dictionary<string k1, Dictionary<string k2, string value>>();
x.fill();

var hashsets = x.Values.Select(i => i.Keys).ToHashSet();

var res=new HashSet<string>();
foreach (var hs in hashsets) res.UnionWith(hs);

是否有一种方法可以在单个linq语句中(没有foreach)计算res?

1 个答案:

答案 0 :(得分:0)

我只是重申@ckuri所说的话:

第一种使用Aggregate的方法:

var result2 = x.Values.Aggregate(new HashSet<string>(), (rs, dic) => { rs.UnionWith(dic.Keys); return rs; });
// meaning: initialize the result with new HashSet<string>
// have the result to do union with each dictionary.keys

使用SelectMany的第二种方法:

var result2 = x.Values.SelectMany(i => i.Keys).ToHashSet();
// flatten the dictionary keys into IEnumerable<string>
// turn that into HashSet

注意:某些人可能不理解您的初始代码,因为它无法编译,并且您缺少最少的代码。我相信应该有ToHashSet()扩展方法才能使此工作正常。仅供参考:

public static class Extensions
{
    public static HashSet<T> ToHashSet<T>(
        this IEnumerable<T> source,
        IEqualityComparer<T> comparer = null)
    {
        return new HashSet<T>(source, comparer);
    }
}