2011-04-22 114 views
0

假設我有一類「Person」 .........獲取所需的對象......

public class Person 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
} 

,並假設我有列表「listOfPerson」含有說15人......

List<Person> listOfPerson = new List<Person>(); 

現在,我試圖讓對象人形成此列表與Max Age ... ..

仔細閱讀我不只是需要最大年齡...... 但整個對象......所以我也可以訪問最大年齡......的人的名字。

感謝.........

回答

4
Person oldest = listOfPerson.OrderByDescending(person => person.Age).First(); 

從評論

並假設我 說....所有最大 年齡的人......有年齡上限(人名單 從給定的人名單)?謝謝

在這種情況下,它是值得的,找到最大年齡,然後過濾它。有各種方法,但一個簡單的方法是

int maxAge = listOfPerson.Max(person => person.Age); 
var oldestPeople = listOfPerson.Where(person => person.Age == maxAge); // .ToList() 

包括可選的擴展ToList()如果這個結果是一個列表,而不是一個IEnumerable<Person>是很重要的。

+1

哈,哈,你用 「無功」!再次擊敗我五秒!完全相同的答案! – 2011-04-22 05:33:09

+0

瞬間滑倒。星期五發生。 – 2011-04-22 05:35:14

+0

@Anthony Pegram ,,假設我說....所有最大年齡的人...(最大年齡從給定人名單的人名單)?謝謝... – Pritesh 2011-04-22 05:48:26

1
listOfPerson.OrderByDescending(x=>x.Age).First(); 
1

如果列表很短,那麼排序並選擇第一個(如前所述)可能是最簡單的。

如果你有一個更長的列表並且排序開始變慢(這可能不太可能),你可以編寫自己的擴展方法來做到這一點(我使用MaxItem,因爲我認爲Max會與現有的LINQ方法衝突,但我懶得弄清楚)。

public static T MaxItem<T>(this IEnumerable<T> list, Func<T, int> selector) { 
    var enumerator = list.GetEnumerator(); 

    if (!enumerator.MoveNext()) { 
     // Return null/default on an empty list. Could choose to throw instead. 
     return default(T); 
    } 

    T maxItem = enumerator.Current; 
    int maxValue = selector(maxItem); 

    while (enumerator.MoveNext()) { 
     var item = enumerator.Current; 
     var value = selector(item); 

     if (value > maxValue) { 
      maxValue = value; 
      maxItem = item; 
     } 
    } 

    return maxItem; 
} 

或者,如果你需要返回所有的最大項目:

public static IEnumerable<T> MaxItems<T>(this IEnumerable<T> list, Func<T, int> selector) { 
    var enumerator = list.GetEnumerator(); 

    if (!enumerator.MoveNext()) { 
     return Enumerable.Empty<T>(); 
    } 

    var maxItem = enumerator.Current; 
    List<T> maxItems = new List<T>() { maxItem }; 
    int maxValue = selector(maxItem); 

    while (enumerator.MoveNext()) { 
     var item = enumerator.Current; 
     var value = selector(item); 

     if (value > maxValue) { 
      maxValue = value; 
      maxItems = new List<T>() { item }; 
     } else if (value == maxValue) { 
      maxItems.Add(item); 
     } 
    } 

    return maxItems; 
}