我希望能够在linq查询中添加if语句以添加第二个LET。有谁知道这是否可能?谢谢
var query = from d in myList
group d by d.Date
into v
let dataSum = nv.Sum(x => x.Data)
select new MyObject(){ Date = nv.Key.Date, Data = dataSum}
//Invalid I know... but something like this is what I'm looking for
var query = from d in myList
group d by d.Date
into v
let dataSum = nv.Sum(x => x.Data)
if(secondaryData){ let dataSum2 = nv.Sum(x.Data2)}
select new MyObject(){ Date = nv.Key.Date, Data = dataSum}
答案 0 :(得分:4)
您可以使用if速记:
let dataSum2 = secondaryData ? nv.Sum(x.Data2) : 0
答案 1 :(得分:1)
试试这个。
List<Product1> prods = new List<Product1>();
prods.Add(new Product1() { ProductPrice = 1, ValidFrom = DateTime.Today });
prods.Add(new Product1() { ProductPrice = 3, ValidFrom = DateTime.Today });
prods.Add(new Product1() { ProductPrice = 2, ValidFrom = DateTime.Today.AddDays(-1) });
prods.Add(new Product1() { ProductPrice = 5, ValidFrom = DateTime.Today.AddDays(-2) });
// Put any logic you want in sumFunc. For any field you want like ProductPrice
Func<Product1, decimal> sumFunc = (p) => p.ProductPrice;
var result = from c in prods
group c by c.ValidFrom into gd
let sum = gd.Sum(sumFunc)
select sum;