我有一个矩形列表“colliedrects”我想将面积最大的矩形传递给函数_playership.Collide() 到目前为止我有......
var item = collidedrects.Max(x => x.Height*x.Width);
_playership.Collide(collidedrects[item]);
我不熟悉 max 以及 C# 中的 => 东西
您可以使用Aggregate
而不是Max
找到最大的矩形:
var largestRect = collidedrects.Aggregate( (r1,r2) =>
(r1.Height * r1.Width) > (r2.Height * r2.Width) ? r1 : r2);
_playership.Collide(largestRect);
问题是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]);