优化LINQ查询以避免多个枚举

时间:2017-06-03 21:15:59

标签: c# asp.net asp.net-mvc linq ienumerable

我在.NET项目中编写了这样的代码:

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

其中“ctx”是我的对象上下文变量...

这是我使用的ViewModelClass:

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

这里最让我烦恼的是销售属性......正如你所看到的,我在select语句中设置了它的值。这样每次都会枚举我的所有数据......

我在想的是创建一个名为“getsales()”的方法......然后只需在我的where语句中调用GetSales方法:

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

为了避免多次枚举......

但我不确定该怎么做......

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

我认为这是你正在寻找的东西:

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