如何将 Linq 的查询结果转为 HashSet ?

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将 Linq 的查询结果转为 HashSet ?相关的知识,希望对你有一定的参考价值。

咨询区

  • Jamie

我的类中有一个 ISet 类型的属性,我想将 linq 查询的结果赋给它,因为是 ISet 类型,所以我不知道是否有高效的方法将 linq 查询结果给之?

简单来说,就像下面这样:

ISet<T> foo = new HashedSet<T>();
foo = (from x in bar.Items select x).SOMETHING;

我在寻找 SOMETHING 这块该如何替代。

回答区

  • Jon Skeet

我觉得 .NET 没有任何内部支持也没关键,大不了自己实现一个扩展方法就好,参考如下代码:

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

有了扩展方法,接下来就可以这么用了。

var query = from i in Enumerable.Range(0, 10)
            select new { i, j = i + 1 };
var resultSet = query.ToHashSet();

除了用扩展方法,其实你也可以用 HashSet<T> 构造函数,比如下面这样。

var query = from i in Enumerable.Range(0, 10)
            select new { i, j = i + 1 };
var resultSet = new HashSet<int>(query);
  • Douglas

你所说的 ToHashSet 扩展方法在 .NET Framework 4.7.2 和 .NET Core 2.0 中已经支持了。

public static HashSet<TSource> ToHashSet<TSource>(this IEnumerable<TSource> source)
{
 return source.ToHashSet(null);
}

public static HashSet<TSource> ToHashSet<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
 if (source == null)
 {
  ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
 }
 return new HashSet<TSource>(source, comparer);
}

可以看到,内部也是用 构造函数 的方式进行转换的。

点评区

其实在很多年前,我就在考虑为什么有 ToList, ToDictionary 方法而没有 ToHashSet,ToQueue,ToStack,后来我想了下,可能程序员在这一块使用频次太低吧,不过现在加进来了,给它点个赞!

以上是关于如何将 Linq 的查询结果转为 HashSet ?的主要内容,如果未能解决你的问题,请参考以下文章