LINQ中通过其他字段和布尔值查询的动态值

问题描述 投票:1回答:2
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对象没有设置器,而这是我编辑值的唯一位置。

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

Amount = prg.Key.Price - 10

我能够获得所需的值,但我还想针对特定类别以及布尔值是否为true进行设置。

c# linq entity-framework linq-to-sql linq-to-entities
2个回答
0
投票

您可以在这里使用三元运算符:

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

0
投票

如果可以的话:

Amount = prg.Key.Price - 10

您也可以这样做:

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

或只是

Amount = prg.Key.Price - ({bool expression} ? 10 : 0)
© www.soinside.com 2019 - 2024. All rights reserved.