Most efficient LINQ result for Contains() query
https://softwareengineering.stackexchange.com/questions/276198
-
07-10-2020 - |
Frage
I currently use the following:
var result = list.Union(otherList).SelectMany(l => l.children).ToList()
foreach(var child in lotsOfChildren){
something = result.Contains(child)
}
I only use result
for querying if the list contains items, using result.Contains(x)
.
This look to be inefficient to me, as, presumably, Contains()
has to enumerate the entire (static) list each time, to check if an item is contained.
I noticed ToDictionary()
and ToLookup()
extension methods, however both these require a key to be defined, which is unnecessary.
I guess what I'm really looking for is a ToHashSet()
sort of thing - would I have to create this manually, as in .ToLookup(c => c.GetHashCode, c => c)
? Or is there a built in method I'm missing? Or, alternatively, is this something the compiler will optimise, and I don't need to care about.
Lösung
You can trivially define an extension method for ToHashSet
if that's what you're looking for.
public static class Extensions
{
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
}
You should now be able to use it in your original example:
var result = list.Union(otherList).SelectMany(l => l.children).ToHashSet()
foreach (var child in lotsOfChildren)
{
something = result.Contains(child)
}