问题描述
我有一个 ISet 类的属性.我正在尝试将 linq 查询的结果获取到该属性中,但不知道该怎么做.
I have a property on a class that is an ISet. I'm trying to get the results of a linq query into that property, but can't figure out how to do so.
基本上,寻找这个的最后一部分:
Basically, looking for the last part of this:
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;
推荐答案
我不认为有任何内置的东西可以做到这一点......但编写扩展方法真的很容易:
I don't think there's anything built in which does this... but it's really easy to write an extension method:
public static class Extensions
{
public static HashSet<T> ToHashSet<T>(
this IEnumerable<T> source,
IEqualityComparer<T> comparer = null)
{
return new HashSet<T>(source, comparer);
}
}
请注意,这里确实需要一个扩展方法(或至少是某种形式的通用方法),因为您可能无法明确表达 T
的类型:
Note that you really do want an extension method (or at least a generic method of some form) here, because you may not be able to express the type of T
explicitly:
var query = from i in Enumerable.Range(0, 10)
select new { i, j = i + 1 };
var resultSet = query.ToHashSet();
您不能通过显式调用 HashSet
构造函数来做到这一点.我们依靠泛型方法的类型推断来为我们做这件事.
You can't do that with an explicit call to the HashSet<T>
constructor. We're relying on type inference for generic methods to do it for us.
现在您可以选择将其命名为 ToSet
并返回 ISet
- 但我会坚持使用 ToHashSet
和具体类型.这与标准 LINQ 运算符(ToDictionary
、ToList
)一致,并允许未来扩展(例如 ToSortedSet
).您可能还想提供指定要使用的比较的重载.
Now you could choose to name it ToSet
and return ISet<T>
- but I'd stick with ToHashSet
and the concrete type. This is consistent with the standard LINQ operators (ToDictionary
, ToList
) and allows for future expansion (e.g. ToSortedSet
). You may also want to provide an overload specifying the comparison to use.
这篇关于如何将 linq 结果转换为 HashSet 或 HashedSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!