首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将linq结果转换为HashSet或HashedSet

如何将linq结果转换为HashSet或HashedSet
EN

Stack Overflow用户
提问于 2010-08-13 04:48:42
回答 6查看 101.6K关注 0票数 210

我在一个是ISet的类上有一个属性。我试图将linq查询的结果放入该属性中,但不知道如何操作。

基本上,寻找这部分的最后一部分:

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

也可以这样做:

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

回答 6

Stack Overflow用户

发布于 2010-08-13 04:51:09

只需将您的IEnumerable传递给HashSet的构造函数。

HashSet<T> foo = new HashSet<T>(from x in bar.Items select x);
票数 83
EN

Stack Overflow用户

发布于 2010-08-13 04:53:57

正如@Joel所说的,你可以直接传入你的enumerable。如果你想做一个扩展方法,你可以这样做:

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
    return new HashSet<T>(items);
}
票数 19
EN

Stack Overflow用户

发布于 2018-05-01 22:19:00

在.NET框架和.NET核心中构建了一个扩展方法,用于将IEnumerable转换为HashSethttps://docs.microsoft.com/en-us/dotnet/api/?term=ToHashSet

public static System.Collections.Generic.HashSet<TSource> ToHashSet<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

似乎我还不能在.NET标准库中使用它(在我写这篇文章的时候)。因此,我使用这个扩展方法:

    [Obsolete("In the .NET framework and in NET core this method is available, " +
              "however can't use it in .NET standard yet. When it's added, please remove this method")]
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer = null) => new HashSet<T>(source, comparer);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3471899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档