Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToHashSet IEnumerable<string>

Tags:

c#

list

I am getting this error not sure why I tried both version using the Template object and just list of string. is there something else I need to do?

HashSet<Template> selectedPatientsHashSet = templates.Select(p => p.VersionKey).ToHashSet<Template>();

var selectedPatientsHashSet = templates.Select(p => p.VersionKey).ToHashSet();

Object type

VersionKey type

[Runtime Error1

like image 767
Jefferson Avatar asked Sep 02 '25 16:09

Jefferson


1 Answers

I'm having the same exact issue. Why the .NET team failed to include the .ToHashSet() extension method in Standard 2.0 is beyond me, as I am also trying to work towards moving some code from .NET Framework 4.8 to .NET. I know the extension method is in .NET Standard 2.1 but that is incompatible with .NET Framework 4.8...this has been a headache to be sure!

My solution was to create my own extension method in my root namespace. Not as "clean" as having the method already available in Linq, but it gets the job done with minimal invasiveness:

public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
   return new HashSet<T>(source, comparer);
}

like image 146
Seth Avatar answered Sep 05 '25 07:09

Seth