How to convert linq results to HashSet or HashedSet

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

    Rather than the simple conversion of IEnumerable to a HashSet, it is often convenient to convert a property of another object into a HashSet. You could write this as:

    var set = myObject.Select(o => o.Name).ToHashSet();
    

    but, my preference would be to use selectors:

    var set = myObject.ToHashSet(o => o.Name);
    

    They do the same thing, and the the second is obviously shorter, but I find the idiom fits my brains better (I think of it as being like ToDictionary).

    Here's the extension method to use, with support for custom comparers as a bonus.

    public static HashSet ToHashSet(
        this IEnumerable source,
        Func selector,
        IEqualityComparer comparer = null)
    {
        return new HashSet(source.Select(selector), comparer);
    }
    

提交回复
热议问题