Linq:如何對集合中所有對象的屬性執行.max(),并返回最大值[的對象我有一個有兩個int屬性的對象列表。該列表是另一個Linq查詢的輸出。對象:public class DimensionPair {
public int Height { get; set; }
public int Width { get; set; }}我想在列表中找到并返回其中最大的對象Height財產價值我可以設法獲得最高值的Height值,而不是對象本身。我能和Linq一起做這個嗎?多么,怎樣?
3 回答

皈依舞
TA貢獻1851條經驗 獲得超3個贊
var item = items.MaxBy(x => x.Height);
MaxBy
):
它是O(N)不像 ,它在每次迭代中找到最大值(使其為O(n^2)。 排序解為O(N Logn) 拿著 Max
值,然后找到帶有該值的第一個元素是O(N),但在序列上迭代兩次。在可能的情況下,您應該以單程方式使用LINQ。 與聚合版本相比,閱讀和理解要簡單得多,并且每個元素只計算一次投影

蕭十郎
TA貢獻1815條經驗 獲得超13個贊
var maxObject = list.OrderByDescending(item => item.Height).First();
list
list
List<T>
IEnumerable<T>
MaxObject
static class EnumerableExtensions { public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector) where U : IComparable<U> { if (source == null) throw new ArgumentNullException("source"); bool first = true; T maxObj = default(T); U maxKey = default(U); foreach (var item in source) { if (first) { maxObj = item; maxKey = selector(maxObj); first = false; } else { U currentKey = selector(item); if (currentKey.CompareTo(maxKey) > 0) { maxKey = currentKey; maxObj = item; } } } if (first) throw new InvalidOperationException("Sequence is empty."); return maxObj; }}
var maxObject = list.MaxObject(item => item.Height);
- 3 回答
- 0 關注
- 3037 瀏覽
添加回答
舉報
0/150
提交
取消