我需要一种方法将多行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
我需要分组方法具体。 提前谢谢
答案 0 :(得分:0)
以下代码应该产生输出,您正在寻找。我在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();
}