Differences in a specific field

I have a class structure:

class MyEx{
public int Prop1;
public int Prop2;
public int Prop3
}

Prop1 and Prop 2 are always the same, Prop3 is changing. this class, which I want to extract from the longer end, should be something like

select new MyEx { Prop1=something;
                  Prop2= something2;
                  Prop3=something3;
}

the problem is that something3 is not unique, so I would like to apply the Distinct to thw query to get the class above with different Prop3 values. But this does not seem to work. Any ideas why? Thanks

+3
source share
2 answers

I think what you want DistinctByfrom MoreLINQ :

var query = items.DistinctBy(x => x.Prop3);
+5
source

Like a bit?

public static class SomeHelperClass
{
    public static IEnumerable<TSource> DistinctBy<TSource, TValue>(
        this IEnumerable<TSource> source, Func<TSource,TValue> selector)
    {
        var hashset = new HashSet<TValue>();
        foreach (var item in source)
        {
            var value = selector(item);
            if (hashset.Add(value)) yield return item;
        }
    }
}

then

var distinct = list.DistinctBy(item => item.Prop3);
+4
source

Source: https://habr.com/ru/post/1769721/


All Articles