2012-11-15 35 views
1

我有一個矩形列表「colliderects」 我想通過最大面積的一個函數_playership.Collide() 到目前爲止,我有...C#,max,找到最大面積列表中的矩形

var item = collidedrects.Max(x => x.Height*x.Width); 
_playership.Collide(collidedrects[item]); 

我不熟悉max和也=>東西在C#

+0

@Justin這不會起作用,因爲'Max'返回最大值,而不是與最大值或物體(如OP的代碼似乎exepct)具有最大值的對象的索引。 – Rawling

回答

4

可以使用Aggregate,而不是Max找到最大的矩形:

var largestRect = collidedrects.Aggregate((r1,r2) => 
    (r1.Height * r1.Width) > (r2.Height * r2.Width) ? r1 : r2); 
_playership.Collide(largestRect); 
+0

今天之前我從來沒有見過這個,現在它出現了兩次。我喜歡它。 (哈,我只是注意到你發佈在同一個問題,因爲我看到這... ... – Rawling

+0

它的工作方式像一個方式...更多功能方面。請糾正我,如果我錯了。同意@Rawling不錯的點點滴滴:) – bonCodigo

0

問題是Max返回您與之比較的值,而不是生成值的項目。如果你創建一個函數MaxBy返回生成該值的項目,那麼它將工作得很好。

public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, 
    Func<TSource, TKey> selector, IComparer<TKey> comparer = null) 
{ 
    comparer = comparer ?? Comparer<TKey>.Default; 
    using (IEnumerator<TSource> sourceIterator = source.GetEnumerator()) 
    { 
     if (!sourceIterator.MoveNext()) 
     { 
      throw new InvalidOperationException("Sequence was empty"); 
     } 
     TSource max = sourceIterator.Current; 
     TKey maxKey = selector(max); 
     while (sourceIterator.MoveNext()) 
     { 
      TSource candidate = sourceIterator.Current; 
      TKey candidateProjected = selector(candidate); 
      if (comparer.Compare(candidateProjected, maxKey) > 0) 
      { 
       max = candidate; 
       maxKey = candidateProjected; 
      } 
     } 
     return max; 
    } 
} 

有了,你可以這樣做:

var item = collidedrects.MaxBy(x => x.Height*x.Width); 
_playership.Collide(collidedrects[item]); 
相關問題