将 Linq 查询求和为一行

本文关键字:一行 Linq 查询 求和 | 更新日期: 2023-09-27 18:35:53

我需要一种方法将多行 linq 查询合并为一行并将所有合并的行求和 .eg

where alldates.years <= Now()

会回来

 Col1   col2  col3  col4  col5  col6
1) 2015     2     1     0    0      4
2) 2014     3     0     1    1      5 
3) 2013     1     1     1    1      1

需要出来作为

 col1  col2  clo3  col4  col5  col6
1) 2015   6     2      2     2    10

我需要具体的分组方法。提前谢谢你

将 Linq 查询求和为一行

以下代码应该生成您正在寻找的输出。我在 Main 方法中使用了测试数据。

    public class Result
    {
        public DateTime col1 { get; set; }
        public int col2 { get; set; }
        public int col3 { get; set; }
        public int col4 { get; set; }
        public int col5 { get; set; }
    }
    public static void Main()
        {
            List<Result> listTest = new List<Result>();
            listTest.Add(new Result() { col1 = DateTime.Now, col2 =1, col3 =3, col4 =5, col5=11});
            listTest.Add(new Result() { col1 = DateTime.Now.AddYears(-1), col2 = 1, col3 = 3, col4 = 5, col5 = 11 });
            listTest.Add(new Result() { col1 = DateTime.Now.AddYears(-1), col2 = 1, col3 = 3, col4 = 5, col5 = 11 });
            var maxYearLessThanCurrentYear = listTest.Where(x => x.col1.Year < DateTime.Now.Year).Select(x => x.col1.Year).Max();
            var output = listTest.Where(x => x.col1.Year < DateTime.Now.Year)
                               .Select( x => new  { x.col2, x.col3, x.col4, x.col5, maxYearLessThanCurrentYear })
                               .GroupBy(x=>x.maxYearLessThanCurrentYear)
                               .Select(x => new Result
                               {
                                   col1 = new DateTime(x.Key, 1, 1) ,
                                   col2 = x.Sum(y => y.col2),
                                   col3 = x.Sum(y => y.col3),
                                   col4 = x.Sum(y => y.col4),
                                   col5 = x.Sum(y => y.col5),
                               })
                               .FirstOrDefault();
     }