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 (2023): There is now an
ToHashSetextension method – see Douglas’ answer below.Original Answer:
I don’t think there’s anything built in which does this… but it’s really easy to write an extension method:
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
Texplicitly: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
ToSetand returnISet<T>– but I’d stick withToHashSetand 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.