如何LINQ结果转换为HashSet的或HashedSet [英] How to convert linq results to HashSet or HashedSet

查看:714
本文介绍了如何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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆