User987
User987

Reputation: 3825

C# LINQ accessing another property within a LINQ SELECT statement (method)

I have a question which refers to whether it's possible to access another property in LINQ in order to set another property's value in LINQ:

  var v = ctx.myTableItems
          .Where(x => x.id== anotherid)
          .Select(e => new MyViewModel
          {
            Title = e.Title,
            CurrentPrice = e.CurrenctPrice.Value,

            ItemID =  e.ItemID.ToString(),
            Transactions= e.Transactions,
            Sales = 
            })
            .Where(x=>x.Sales>0);

So check this out guys, when I was setting my Transactions property I set the transactions collection in my previous line, and now I'd like to set my sales propert with the Transactions property that was assigned in a previous line:

  Transactions= e.Transactions,
  Sales = e.Transactions.Sum(x=>x.Quantity) // Normaly I'd do it like this

But I wanted to try out something like this:

 Sales = Transactions.Sum(x=>x.Quantity) // is this doable ?

So my question here is, is it possible to set another property within the select statement with a previously property's value? In my case it's Transactions collection ?

Is this doable, if so , how?

P.S. I'm trying to figure if this is doable because if I could use this previously set property's value , then I would avoid performing 2 unnecesary queries on my Transactions table in DB?

Upvotes: 1

Views: 748

Answers (1)

Max Payne
Max Payne

Reputation: 95

You cannot use the previous value because you dont want to call e.Transactions.Sum() for every item.

Just add a method to MyViewModel

public double GetSales()
{
 return Transactions.Sum(x=>x.Quantity);
}

//at the end of your code use:
.Where(x=>x.GetSales()>0);

Upvotes: 2

Related Questions