I have data with the following shape
someArray = [{ Name: "Some Class", TypeEnum: "Default" },
{ Name: "Some Class", TypeEnum: "Other" },
{ Name: "Some Class 2", TypeEnum: "Default" },
{ Name: "Some Class 2", TypeEnum: "Other" },
{ Name: "Some Class 3", TypeEnum: "Default" },
{ Name: "Some Class 4", TypeEnum: "Not Other" }]
Imagine each of those as objects in C#
What I need is an array of distinct versions of that array, with preference given to a selected TypeEnum. For example if I have selected the TypeEnum of other, I still want it to default to Default if it can’t find a version of that class with the “Other” TypeEnum
e.g. With “Other” selected as the Type enum, the above data would look like
[{ Name: "Some Class", TypeEnum: "Other" },
{ Name: "Some Class 2", TypeEnum: "Other" },
{ Name: "Some Class 3", TypeEnum: "Default" }]
What I’m doing now is a lambda comparison from here
TypeEnum myEnum = "Other"
someArray.Distinct((x,y) => x.Name == y.Name &&
x.TypeEnum != myEnum &&
(y.TypeEnum == myEnum || y.TypeEnum == "Default"));
I’m hoping that Distinct pops out any x from the array that get’s a true from that expression.
Am I wrong in how I think Distinct works. If I am, what should I use instead?
You can define a
Comparer<T>class to handle your preference for comparison, like this:UPDATE:
If you’re only interested in the elements with your preferred or Default
TypeEnum, you could filter out the rest first. Then sort the array according to the Comparer, i.e. giving preferredTypeEnumhigher precedence than Default. Finally group the objects by their Name, and take the first one from each group:Or you can use the following version if you don’t want to define a Comparer class: