Linq不同的方法仅适用于特定属性

时间:2013-12-20 13:32:40

标签: c# linq

在此代码段中,如何在选择所有其他值[ e.Firstname, e.Surname, e.EntityNumber ]时仅对e.EntityNumber使用不同的功能。

response
   .Categories
   .SelectMany(c => c.Events)
   .Select(e => new { e.Firstname, e.Surname, e.EntityNumber })
   .Distinct()
   .ToList()

2 个答案:

答案 0 :(得分:3)

您可以改为使用GroupBy

response
   .Categories
   .SelectMany(c => c.Events)
   .Select(e => new { e.Firstname, e.Surname, e.EntityNumber })
   .GroupBy(x => x.EntityNumber)
   .Select(grp => grp.First())
   .ToList()

我选择了每组的任意一行(第一组)。您可以根据自己的逻辑更改grp.First()

//...
.GroupBy(x => x.EntityNumber)
.Select(grp => grp.OrderBy(x => /* Insert logic here */).First())
//...

答案 1 :(得分:2)

您可以实施扩展方法DistinctBy

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null)
{
    if (source == null) throw new ArgumentNullException("source");
    if (keySelector == null) throw new ArgumentNullException("keySelector");

    var keys = new HashSet<TKey>(comparer);
    foreach (var element in source)
    {
        if (keys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}