我在一个类上有一个属性,它是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;

当前回答

在.NET框架和.NET核心中有一个用于将IEnumerable转换为HashSet的扩展方法:https://learn.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);

其他回答

乔恩的回答很完美。唯一需要注意的是,使用NHibernate的HashedSet,我需要将结果转换为一个集合。有没有最佳的方法来做到这一点?

ISet<string> bla = new HashedSet<string>((from b in strings select b).ToArray()); 

or

ISet<string> bla = new HashedSet<string>((from b in strings select b).ToList()); 

还是我还遗漏了什么?


编辑:这是我最后做的:

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
    return new HashSet<T>(source);
}

public static HashedSet<T> ToHashedSet<T>(this IEnumerable<T> source)
{
    return new HashedSet<T>(source.ToHashSet());
}

如果您只需要对集合进行只读访问,并且源是方法的参数,那么我会选择

public static ISet<T> EnsureSet<T>(this IEnumerable<T> source)
{
    ISet<T> result = source as ISet<T>;
    if (result != null)
        return result;
    return new HashSet<T>(source);
}

原因是,用户可能已经使用ISet调用您的方法,因此您不需要创建副本。

正如@Joel所说,你可以只传入你的枚举值。如果你想做一个扩展方法,你可以这样做:

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

这很简单:)

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

T是OP指定的类型:)

在.NET框架和.NET核心中有一个用于将IEnumerable转换为HashSet的扩展方法:https://learn.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);