1

我有一个如下列表

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  
4

2 回答 2

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
}
于 2013-02-06T12:25:25.920 回答
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()
于 2013-02-06T12:15:06.950 回答