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

当前回答

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

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调用您的方法,因此您不需要创建副本。

其他回答

此功能已作为IEnumerable<TSource>上的扩展方法添加到. net Framework 4.7.2和. net Core 2.0中。因此,在. net 5及更高版本中也可以使用它。

ToHashSet < TSource > (IEnumerable < TSource >) ToHashSet < TSource > (IEnumerable < TSource >, IEqualityComparer < TSource >)

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

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);
}

在.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);

这很简单:)

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

T是OP指定的类型:)