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

当前回答

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

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

其他回答

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

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

乔恩的回答很完美。唯一需要注意的是,使用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());
}

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

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

与其简单地将IEnumerable转换为HashSet,还不如将另一个对象的属性转换为HashSet。你可以这样写:

var set = myObject.Select(o => o.Name).ToHashSet();

但是,我更倾向于使用选择器:

var set = myObject.ToHashSet(o => o.Name);

它们做的是同样的事情,而且第二个明显更短,但我发现这个习语更适合我的大脑(我认为它就像ToDictionary)。

下面是要使用的扩展方法,支持自定义比较器作为奖励。

public static HashSet<TKey> ToHashSet<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> selector,
    IEqualityComparer<TKey> comparer = null)
{
    return new HashSet<TKey>(source.Select(selector), comparer);
}