How to convert linq results to HashSet or HashedSet

前端 未结 9 710
闹比i
闹比i 2020-11-28 05:17

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, look

相关标签:
9条回答
  • 2020-11-28 05:58

    If you need just readonly access to the set and the source is a parameter to your method, then I would go with

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

    The reason is, that the users may call your method with the ISet already so you do not need to create the copy.

    0 讨论(0)
  • 2020-11-28 06:06

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

    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.

    0 讨论(0)
  • 2020-11-28 06:08

    Just pass your IEnumerable into the constructor for HashSet.

    HashSet<T> foo = new HashSet<T>(from x in bar.Items select x);
    
    0 讨论(0)
提交回复
热议问题