我有一个如下所示的列表
Name Score Date
S1 2 15/02/2013
S1 4 15/02/2013
S2 0 15/02/2013
My desired out should be
S1 6 15/02/2013
为此我将LINQ代码写为
(from _data in _rawData
group _data by new { _data.Date, _data.Name } into gp orderby gp.Key.Date
select new
{
score = gp.Sum(_score => _score.Score),
store = gp.Max(_store => _store.Name),
Date = gp.Max(_Date => _Date.Date)
}).OrderByDescending(_score => _score.score)
.ToList().
ForEach(item => _timeLiner.Add(new TimeLiner()
{
id = _id++.ToString(),
start = item.auditDate.ToString(),
title = "TopStore: " + item.store
}
我尝试使用.Take(1).ToList()
,Single()
,SingleOrDefault()
,First()
,但未能获得所需的输出。相反,我得到了
S1 6 15/02/2013
S2 0 15/02/2013
答案 0 :(得分:1)
top
是一个新的范围变量,它保存一天最高分名称的摘要数据
from d in _rawData
group d by d.Date into dateGroup
let top = dateGroup.GroupBy(x => x.Name)
.Select(g => new { Name = g.Key, Score = g.Sum(x => x.Score)})
.OrderByDescending(x => x.Score)
.First()
select new
{
Name = top.Name,
Score = top.Score,
Date = dateGroup.Key
}
答案 1 :(得分:0)
以下内容应该为您提供所需的输出:
(from _data in _rawData
group _data by new { _data.Date, _data.Name } into gp orderby gp.Key.Date
select new
{
score = gp.Sum(_score => _score.Score),
store = gp.Max(_store => _store.Name),
Date = gp.Max(_Date => _Date.Date)
}).OrderByDescending(_score => _score.score)
.First();
或者,更具可读性:
_rawData.GroupBy(x => new { x.Date, x.Name })
.Select(g => new {
Score = g.Sum(x => x.Score),
Store = g.Key.Name,
Date = g.Key.Date
}
.OrderByDescending(x => x.Score)
.First()