I see youâre already using linq here, and with linq you have the âDistinctâ method:
One of its overloads takes in an IEqualityComparer (unfortunately it doesnât take in a Comparison delegate, but so it goes).
So I created a simple IEqualityComparer that compares the names:
class SealNameEqualityComparer : IEqualityComparer<Seal>
{
public static readonly SealNameEqualityComparer Default = new SealNameEqualityComparer();
public bool Equals(Seal x, Seal y)
{
return x.Name == y.Name;
}
public int GetHashCode(Seal obj)
{
return obj.Name != null ? obj.Name.GetHashCode() : 0;
}
}
And here you go:
var realRet = baseList.Distinct(SealNameEqualityComparer.Default).ToList();
Note, you could do this all in linq like so:
var realRet Slots.Where(item => item.ThisSeal != null && !string.IsNullOrEmpty(this.SealName.Name) && item.ThisSeal.SealCondition != null)
.Select(item => item.ThisSeal)
.Distinct(SealNameEqualityComparer.Default)
.ToList();
âŚ
In an aside, the reason youâre getting that exception is that the âSelectâ linq method doesnât return a List, it returns an IEnumerable:
You canât cast that to List, because itâs not a List. Rather itâs an object that when enumerated performs the âSelectâ.
Use âToListâ to take the result of that enumeration and stick it in a List:
But yeah⌠back at my example, I removed the need for GroupBy Select First.
You can continue using that. But it requires more objects to be created than Distinct, and will perform slower (though on small lists it wonât matter).
Go here to the Enumerable source code to see the complexity differences:
https://referencesource.microsoft.com/#system.core/System/Linq/Enumerable.cs
Distinct just uses a âHashSetâ (which explains why it only takes an IEqualityComparer, it feeds that to the HashSet), and then uses that set to generate a Distinct list since HashSets canât have duplicates in them and have O(1) lookup.
Where as GroupBy does⌠a lot⌠it generates a âGroupedEnumerableâ object, that generates a âLookupâ object which creates an internal array to store the groupings, and performs quite a bit of logic.