c#从列表<object> </object>获取min,max和average

时间:2014-11-21 08:39:13

标签: c#

我有List<Order>

public class Order
{
   public Order()
   {
   }

   public string UserId {get; set;}
}

我希望能够使用LINQ获取以下信息:

  • 订单次数最多的UserId
  • 订单次数最少的UserId
  • 所有订单的平均值

所以结果应该是这样的:

  • UserId:1有20个订单(最多)
  • UserId:2有5个订单(分钟)
  • 平均12.5个订单

3 个答案:

答案 0 :(得分:1)

您可以使用Lookup

var userLookup = orderList.ToLookup(o => o.UserId);
int maxOrders = userLookup.Max(x => x.Count());
int minOrders = userLookup.Min(x => x.Count());
int avgOrders = (int)userLookup.Average(x => x.Count());
IEnumerable<string> allUserIDsWithMaxOrders = userLookup
    .Where(x => x.Count() == maxOrders)
    .Select(g => g.Key);
IEnumerable<string> allUserIDsWithMinOrders = userLookup
    .Where(x => x.Count() == minOrders)
    .Select(g => g.Key);
IEnumerable<string> allUserIDsWithAvgOrders = userLookup
    .Where(x => x.Count() == avgOrders)
    .Select(g => g.Key);

但是,我不清楚你想要获得单个用户的平均订单数量,这不总是绝对值吗?

答案 1 :(得分:1)

按userId创建群组并使用它们。

var groups = allOrders.GroupBy(o => o.UserId);
int userWithMostOrders = groups.OrderByDescending(g => g.Count()).First().Key;
double averageOrders = allOrders.Count() / groups.Count();

答案 2 :(得分:1)

var userWithLeastOrders = ordens.GroupBy(o => o.UserId)
                                .OrderBy(group => group.Count())
                                .First()
                                .Key;

你应该能够解决其他问题。