C#,max,在列表中找到面积最大的矩形

时间:2012-11-15 16:01:09

标签: c# max

我有一个矩形列表“collidedrects” 我想将具有最大区域的那个传递给函数_playership.Collide() 到目前为止,我有......

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

我不熟悉max和=> C#中的东西

2 个答案:

答案 0 :(得分:4)

您可以使用Aggregate代替Max来查找最大的矩形:

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

答案 1 :(得分: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]);