使用Linq从数据库中获取Min和Max

时间:2016-07-19 12:18:19

标签: c# linq

在数据库中我有:

    Name         Value
    First Player   300
    First Player   500
    First Player   250
    SecondPlayer   200
    Second Player  450

我需要向每位玩家展示最大和最小值:

Name       MaxValue   MinValue
FirstPlayer   500        250
SecondPlayer   450       200

我这样做了:

var res = (from item in _context.Players
          select item).Max(s=>s.Value);

但它只有一个具有最大值的玩家;

2 个答案:

答案 0 :(得分:7)

查询语法:

var result = (from item in _context.Players
group item by name into @group
select new 
{ 
    Name = @group.Key, 
    MaxValue = @group.Max(i=>i.Value), 
    MinValue = @group.Min(i=>i.Value)
}).ToList();

或者使用一个很好的linq方法语法:(这个重载基本上可以让你在“.Select()

中执行.GroupBy()
var result = _context.Players.GroupBy(item => item.Name, (key, @group) => new
        {
            Name = key,
            MaxValue = @group.Max(i => i.Value),
            MinValue = @group.Min(i => i.Value)
        }).ToList();

答案 1 :(得分:4)

使用Select的GroupBy应该工作:

var res = _context.Players.GroupBy(x=> x.Name)
                  .Select(x=> new 
                          { 
                                Name = x.Key, 
                                Max = x.Max(y=> y.Value), 
                                Min = x.Min(y=> y.Value) 
                          }).ToList();

或使用查询语法

var res = (from p in _context.Players
            group p by p.Value into grp
            select new
            {
                Name = grp.Key,
                Max = grp.Max(rec => rec.Value),
                Min = grp.Min(rec => rec.Value)
            }).ToList();