开发者

Distinct on 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 varies. this class I want to retrieve from a longer the end should be something like

select n开发者_Python百科ew MyEx { Prop1=something;
                  Prop2= something2;
                  Prop3=something3;
}

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


I think you want DistinctBy from MoreLINQ:

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


A bit like so?

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜