我有List<Order>
public class Order
{
public Order()
{
}
public string UserId {get; set;}
}
我希望能够使用LINQ获取以下信息:
UserId
UserId
所以结果应该是这样的:
答案 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;
你应该能够解决其他问题。