linq查询中的动态值由其他字段和布尔值组成

时间:2015-08-19 18:37:26

标签: c# linq entity-framework linq-to-sql linq-to-entities

var results = 
    (from p in DBContext.Sources
    orderby p.AccountTypeId
    group p by new { p.AccountTypeId } into g
    select new ObjectItem
    {
        AccountTypeId = g.Key.AccountTypeId,
        Packages = 
            (from pkg in g
            group pkg by new
            {
                pkg.PackageId,
                pkg.Enabled
            } into pg
            select new ATSourcePackageItem
            {
                PackageId = pg.Key.PackageId,
                DisplayName = pg.Key.DisplayName,
                CategoryId = pg.Key.DisplayCategoryId,
                Prices = 
                    (from pr in pg
                    group pr by new { pr.Fpt, pr.Price } into prg
                    select new ATSourcePriceItem
                    {
                        FPT = prg.Key.Fpt,
                        Amount = prg.Key.Price
                    })
            })
    }).ToList();

Amount等于7且条件为真时,我想将CategoryId减去10。

是否有可能以某种方式在此linq查询中执行此操作,因为Amount对象没有setter,这是我可以编辑值的唯一位置。

例如,如果我做了类似的事情:

Amount = prg.Key.Price - 10

我能够获得我想要的值,但我也想为特定类别设置它,如果布尔值为真。

由于

2 个答案:

答案 0 :(得分:0)

如果你能做到这一点:

Amount = prg.Key.Price - 10

你也可以这样做:

Amount = {bool expression} ? prg.Key.Price - 10 : prg.Key.Price

或只是

Amount = prg.Key.Price - ({bool expression} ? 10 : 0)

答案 1 :(得分:0)

您可以在此处使用三元运算符:

//Amount = prg.Key.Price
Amount = (pg.Key.DisplayCategoryId == 7 && your_boolean_here) ? 
    prg.Key.Price - 10 : prg.Key.Price