How to convert linq results to HashSet or HashedSet

前端 未结 9 760
闹比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:42

    There is an extension method build in the .NET framework and in .NET core for converting an IEnumerable to a HashSet: https://docs.microsoft.com/en-us/dotnet/api/?term=ToHashSet

    public static System.Collections.Generic.HashSet ToHashSet (this System.Collections.Generic.IEnumerable source);
    

    It appears that I cannot use it in .NET standard libraries yet (at the time of writing). So then I use this extension method:

        [Obsolete("In the .NET framework and in NET core this method is available, " +
                  "however can't use it in .NET standard yet. When it's added, please remove this method")]
    public static HashSet ToHashSet(this IEnumerable source, IEqualityComparer comparer = null) => new HashSet(source, comparer);
    

提交回复
热议问题