按日期分组,包括最大值和评论列表

时间:2018-08-29 04:43:06

标签: c# linq group-by

我有以下结果表:

| id | t_id| value | comment |    date    |
-------------------------------------------
| 1  |  1  |   10  |  test1  | 01-01-2018 |
| 2  |  1  |   20  |  test2  | 01-01-2018 |
| 3  |  1  |   30  |  test3  | 01-01-2018 |
| 4  |  2  |   10  |  NULL   | 01-02-2018 |
| 5  |  2  |   10  |  test5  | 01-03-2018 |

我上课的结果是:

public class ChartResult
{
    public DateTime X { get; set; }
    public double Y { get; set; }
    public List<string> Comments { get; set; }
}

如何按日期对结果进行分组,返回每个组的最后一个值和注释列表,并将此结果映射到ChartResult对象的列表中?

2 个答案:

答案 0 :(得分:0)

我会通过将其破坏为:

class Program
    {
        static void Main(string[] args)
        {
            var masterData = new List<Data>
            {
                new Data{ id = 1, t_id =1, value = 10, comment="test1", date=Convert.ToDateTime("01-01-2018") },
                new Data{ id = 2, t_id =1, value = 10, comment="test2", date=Convert.ToDateTime("01-01-2018") },
                new Data{ id = 3, t_id =1, value = 10, comment="test3", date=Convert.ToDateTime("01-01-2018") },
                new Data{ id = 4, t_id =2, value = 10, comment=null, date=Convert.ToDateTime("01-02-2018") },
                new Data{ id = 5, t_id =2, value = 10, comment="test5", date=Convert.ToDateTime("01-03-2018") },
            };

            var chartResults = new List<ChartResult>();

            foreach (var date in masterData.Select(i => i.date).Distinct().ToList())
            {
                var commentsForDate = masterData.Where(i => i.date == date).Select(i => i.comment).ToList();
                var maxValue = masterData.Where(i => i.date == date).Max(i => i.value);
                chartResults.Add(new ChartResult
                {
                    Comments = commentsForDate,
                    X = date,
                    Y = maxValue
                });
            }
        }
    }

    public class ChartResult
    {
        public DateTime X { get; set; }
        public double Y { get; set; }
        public List<string> Comments { get; set; }
    }


    public class Data
    {
        public int id { get; set; }
        public int t_id { get; set; }
        public int value { get; set; }
        public string comment { get; set; }
        public DateTime date { get; set; }
    }

答案 1 :(得分:0)

我假设您的c#变量中已经有来自SQL的数据。我只是建议将数据处理为所需格式

假设您的数据位于类似的类对象myData中

public class Data
{
   public int id { get; set; }
   public int t_id { get; set; }
   public int value { get; set; }
   public string comment { get; set; }
   public DateTime date { get; set; }
}

数据myData;

您需要的课程是

public class ChartResult
{
    public DateTime X { get; set; }
    public double Y { get; set; }
    public List<string> Comments { get; set; }
}

myData.GroupBy(x => x.Date).Select(gp => new CharResult(){ X = gp.Key, Y = gp.Max(p => p.value), Comments = gp.Select(p => p.comment).ToList() })