简体   繁体   中英

How do I capture a variable in Linq method syntax?

I have the following Linq query...

Proposals.OrderByDescending (p => p.ID)
  .First ()
  .Proposal_ProductConfigurations
  .Select(ppc => ppc.ProductConfigurationHistory)
  .Where(pch => pch.Active)
  .Select(pch => pch.ProductConfiguration)
  .Where(pc => pc.Active)
  .SelectMany(pc => pc.ProductConfigurations_PriceBookEntries)
  .Where(pcpb => pcpb.Active)
  .OrderBy(pcpb => pcpb.PriceBook.ProductCode)
  .GroupBy(pcpb => pcpb.PriceBook.ID)
  .Select (pcpb => new {
    Code = pcpb.First().PriceBook.ProductCode,
    Description = pcpb.First().PriceBook.Description,
    Quantity = pcpb.Sum (pcpb1 => (pcpb1.Quantity ?? 0)),
  })

...which is not quite right, as the ppc.Quantity entity has a Quantity property that needs to be used in the last line.

What I really want to do is something line this...

Quantity = pcpb.Sum (pcpb1 => (pcpb1.Quantity ?? 0) * ppc.Quantity),

...but of course I can't, as ppc is not in scope.

How would I capture the ppc.Quantity and use it in the last line? I think this could be done with fluent syntax, but I never use it, and haven't managed to produce any code that the compiler liked!

First you can simplify the following part

.Select(ppc => ppc.ProductConfigurationHistory)
.Where(pch => pch.Active)
.Select(pch => pch.ProductConfiguration)
.Where(pc => pc.Active)

to

.Where(ppc => ppc.ProductConfigurationHistory.Active
              && ppc.ProductConfigurationHistory.ProductConfiguration.Active)

And you'll maintain the resulting collection of ppc instead of pc .

At this point you'll want to use the SelectMany overload that has a result selector as well as a collection selector to keep the ppc

.SelectMany(
    ppc => ppc.ProductConfigurationHistory
              .ProductConfiguration
              .ProductConfigurations_PriceBookEntries,
    (ppc, pcpb) => new { ppc, pcpb })

Then you just have to work with that new anonymous class and you'll get this

Proposals.OrderByDescending (p => p.ID)
  .First ()
  .Proposal_ProductConfigurations
  .Where(ppc => ppc.ProductConfigurationHistory.Active
                && ppc.ProductConfigurationHistory.ProductConfiguration.Active)
  .SelectMany(
    ppc => ppc.ProductConfigurationHistory
              .ProductConfiguration
              .ProductConfigurations_PriceBookEntries,
    (ppc, pcpb) => new { ppc, pcpb })
  .Where(anon => anon.pcpb.Active)
  .OrderBy(anon => anon.pcpb.PriceBook.ProductCode)
  .GroupBy(anon => anon.pcpb.PriceBook.ID)
  .Select (grp => new {
    Code = grp.First().pcpb.PriceBook.ProductCode,
    Description = grp.First().pcpb.PriceBook.Description,
    Quantity = grp.Sum(anon => (anon.pcpb.Quantity ?? 0) * anon.ppc.Quantity),
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM