简体   繁体   中英

Optimizing LINQ Query to avoid multiple enumerations

I have written a code like this in my .NET project:

var v = ctx.Items
        .Where(x => x.userid== user.userid)
        .Select(e => new MyViewModel
        {
          Title = e.Title,
          CurrentPrice = e.CurrenctPrice.Value,
          ItemID = e.ItemID.ToString(),
          Sales = e.Transactions.Where(p => p.TransactionDate >= intoPast && p.TransactionDate <= endDate).Sum(x => x.QuantityPurchased)
         })
         .Where(x => x.Sales > 0 && ((filterWord == "") || (filterWord != "" && x.Title.ToLower().Contains(filterWord.ToLower()))));

where "ctx" is my object context variable...

And this is the ViewModelClass that I use:

  public class MyViewModel
    {
        public string Title { get; set; }
        public int Sales { get; set; }
        public string ItemID { get; set; }
        public double CurrentPrice { get; set; }
    }

The thing that most bugs me here is the sales property... As you can see i set its value in select statement. This way all my data gets enumerated every time...

What I was thinking here is to create a method called "getsales()"... And then to just simply call the GetSales method in my where statement like this:

.Where(x=>X.GetSales(/*neccesary parameters here*/)...)

In order to avoid having multiple enumerations...

But I'm not really sure how to do it...

Can someone help me out here?

I think this is what you're looking for:

var v = ctx.Items
    .Where(x =>
        x.userid == user.userid &&
        (filterWord == "" || x.Title.ToLower().Contains(filterWord.ToLower())))
    .Select(e => new MyViewModel
    {
        Title = e.Title,
        CurrentPrice = e.CurrentPrice.Value,
        ItemID = e.ItemID.ToString(),
        Sales = e.Transactions
            .Where(p => 
                p.TransactionDate >= intoPast && 
                p.TransactionDate <= endDate)
            .Sum(x => x.QuantityPurchased)
    })
    .Where(x => x.Sales > 0);

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