如何LINQ结果转换为HashSet的或HashedSet

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

我有一类就是一个ISet的一个属性。我试图让LINQ查询到该物业的结果,但无法弄清楚如何做到这一点。

基本上,寻找这最后一部分:

的ISet< T>富=新HashedSet< T>();富=(从bar.Items选择X X).SOMETHING;

也可以这样做:

的HashSet< T>富=新的HashSet< T>();富=(从bar.Items选择X X).SOMETHING;

编辑:这是我落得这样做:

公共静态的HashSet< T> ToHashSet< T>(这个IEnumerable的< T>源){    返回新的HashSet< T>(源);}公共静态HashedSet< T> ToHashedSet< T>(这个IEnumerable的< T>源){    返回新HashedSet< T>(source.ToHashSet());}

解决方案

我不的认为的有什么内置在其中做到这一点......但它真的很容易写一个扩展方法:

公共静态类扩展{    公共静态的HashSet< T> ToHashSet< T>(这个IEnumerable的< T>源)    {        返回新的HashSet< T>(源);    }}

请注意,你真的想要一个扩展方法(或至少是某种形式的一般方法)在这里,因为你可能无法前preSS T类型明确:

VAR的查询=从我在Enumerable.Range(0,10)            选择新的{I,J = I + 1};变种的resultSet = query.ToHashSet();

您不能这样做具有显式调用的HashSet< T> 构造函数。我们依靠类型推断为泛型方法为我们做到这一点。

现在您的可能的选择将它命名为 ToSet 并返回的ISet< T> - 但我与 ToHashSet 和具体类型棒。这是标准的LINQ运营商一致的( ToDictionary ,了ToList ),并允许为将来的扩展(如 ToSortedSet )。您可能还需要提供一个超负荷指定要使用的比较。

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;

Could also do this:

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

Edit: This is what I ended up doing:

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

解决方案

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) { return new HashSet<T>(source); } }

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

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.

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:53:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574144.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   LINQ   HashedSet   HashSet

发布评论

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

>www.elefans.com

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