2013-12-20 44 views
0

在此代碼片段中,如何在爲e.EntityNumber使用不同功能時選擇所有其他值[ e.Firstname, e.Surname, e.EntityNumber ]只針對特定屬性的Linq不同方法

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

另請參閱[爲什麼沒有LINQ的方法,通過一個謂詞返回不同的值?(http://stackoverflow.com/questions/520030/why-is-there-no-linq-method-to-return-distinct-values-by-a-predicate) –

回答

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()) 
//... 
+0

對不起,太斜了:) – Rawling

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; 
     } 
    } 
} 
相關問題