Search code examples
c#linqentity-frameworklinq-to-sqllinq-to-entities

Dynamic values in linq query by other field and boolean value


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();

I want to subtract Amount by 10 when CategoryId equals 7 and when a condition is true.

Is it possible to somehow do this within this linq query because the Amount object doesn't have a setter and this is the only place how I can edit the value.

For example if I do something like:

Amount = prg.Key.Price - 10

I'm able to get the value I want, but I want also to set that for specific category and if the boolean value is true.


Solution

  • You can use a ternary operator here :

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