-1

我希望能够将 if 语句添加到 linq 查询中以添加第二个 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}
4

2 回答 2

4

您可以使用 if 速记:

let dataSum2 = secondaryData ? nv.Sum(x.Data2) : 0
于 2012-07-24T14:46:10.323 回答
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;
于 2012-07-24T16:17:22.210 回答