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

编程入门 行业动态 更新时间:2024-10-18 12:23:12
本文介绍了如何将 linq 结果转换为 HashSet 或 HashedSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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

本文发布于:2023-11-10 02:52:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574143.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   HashedSet   linq   HashSet

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!