簡體   English   中英

用linq計算列表屬性的總和,不包括最小值和最大值

[英]calculate sum of list properties excluding min and max value with linq

這是我到目前為止的內容:

decimal? total = list.Sum(item => item.Score);

我想做的是排除列表中的最小值和最大值,然后得到總值。

是否可以在一個linq語句中完成所有這些操作?

list.OrderBy(item => item.Score)
    .Skip(1)
    .Reverse()
    .Skip(1)
    .Sum(item => item.Score);

您可以先嘗試排序列表,然后跳過第一項(最小),並從其余項中取出除最后一項(最大)之外的所有內容:

decimal? total = list.OrderBy(x => x.Score)
                     .Skip(1)
                     .Take(list.Count - 2)
                     .Sum(x => x.Score);

這不是可以想象的最好的代碼,但是它確實具有以下優點:

  • 僅枚舉整個集合一次 (盡管它確實會獲得第一個值三次)。
  • 不需要更多的內存來容納IEnumerator和兩個Tuple<int, int, long, long>對象(如果使用OrderByToList和sorting等,則沒有此對象)。 這使它可以處理任意大的IEnumerable集合。
  • 單個Linq表達式(這就是您想要的)。
  • 正確處理邊緣情況( values.Count() < 2 ):
    • 當沒有值時,在IEnumerable上使用Min()Max()會引發InvalidOperationException
    • 當有一個值時,簡單的實現將對IEnumerable執行類似Sum() - Min() - Max() ,該操作將返回單個值(取反)。

我知道您已經接受了答案,但是這里是:我正在使用一次對Enumerable.Aggregate的調用。

public static long SumExcludingMinAndMax(IEnumerable<int> values)
{
    // first parameter: seed (Tuple<running minimum, running maximum, count, running total>)
    // second parameter: func to generate accumulate
    // third parameter: func to select final result
    var result = values.Aggregate(
            Tuple.Create<int, int, long, long>(int.MaxValue, int.MinValue, 0, 0),
            (accumulate, value) => Tuple.Create<int, int, long, long>(Math.Min(accumulate.Item1, value), Math.Max(accumulate.Item2, value), accumulate.Item3 + 1, accumulate.Item4 + value),
            accumulate => accumulate.Item3 < 2 ? 0 : accumulate.Item4 - accumulate.Item1 - accumulate.Item2);

    return result;
}

如果要排除所有最小值和最大值,請預先計算兩個值,然后使用Ènumerable.Where

decimal? min = list.Min(item => item.Score);
decimal? max = list.Max(item => item.Score);
decimal? total = list
    .Where(item=> item.Score != min && item.Score != max)
    .Sum(item =>  item.Score);

您應在匯總之前對列表進行預處理,以排除最小值和最大值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM