c# - linq中的switch case

标签 c# entity-framework linq switch-statement

我有一个像这样的 linq 查询

 var tmp = (from t in db.sometable
            where (bunch of conditions)
            group t by new { t.somefield} into g
            select new
            {                               
                Name = g.Key.someobject.Name,
                xColor = g.Sum(a => (int?)a.LineItems.Where(m => m.Product == "x" && m.Color == true)
                                                     .Sum(m => m.Quantity)),
                xBW = g.Sum(a => (int?)a.LineItems.Where(m => m.Product == "x" && m.Color == false)
                                                  .Sum(m => m.Quantity))    
            })

现在我想优化这个查询。如果我必须写一个存储过程,我会写这样的东西:

if(a.LineItems.Product == 'x')
{
   if(m.Color == true)
     xColor++;
   else
     xBW++;
}

这样我就可以在一次扫描中获得聚合值。基本上我想优化这个查询以避免多次扫描。

最佳答案

Linqpad 中查看这个简单的代码片段,它按照您期望的方式在 visual studio 中运行,删除 Dump方法调用。我为一个简单的演示简化了类结构,它只是一个 POCO , 不是 complex type包含另一个 list里面

void Main()
{
    var testList = Test.CreateList();

    var tmp = (from t in testList
               group t by new { t.Name } into g
               select new
               {
                   Name = g.Key.Name,
                   xColor = g.Sum(a =>
                   {
                       if (a.Product == "x" && a.Color == true)
                           return a.Quantity;
                       return 0;
                   }),
                    xBW = g.Sum(a =>
                   {
                       if (a.Product == "x" && a.Color == false)
                           return a.Quantity;
                       return 0;
                   })
               });

    tmp.Dump();
}

public class Test
{
    public string Name { get; set; }

    public string Product { get; set;}

    public bool Color { get; set;}

    public int? Quantity { get; set;}

    public static List<Test> CreateList()
    {
        return new List<Test>()
        {
          new Test {Name="A",Color = true,Product="x",Quantity=5},
          new Test {Name="A",Color = true,Product="x",Quantity=5},
          new Test {Name="A",Color = true,Product="x",Quantity=5},
          new Test {Name="B",Color = true,Product="x",Quantity=5},
          new Test {Name="B",Color = true,Product="x",Quantity=5},
          new Test {Name="B",Color = true,Product="x",Quantity=5}         
        };
    }
}

但是这是否有效还有待商榷

关于c# - linq中的switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36548768/

相关文章:

c# - 强制 WPF 应用程序在 Windows 启动时最大化

.net - Reload() 不更新 EF 实体

c# - 如何压缩两个不同大小的列表以创建一个与原始列表中最长的列表相同的新列表?

c# - 从字符串数组中搜索并忽略完全匹配的字符串

c# - 使用 .NET 4.0 编译器编译 .NET 3.5 项目

c# - 如何使 .NET Web Api 仅对我的应用程序私有(private)

sql-server - 使用用户通过 Entity Framework 提供的 XPath 查询 SQL Server xml 列

sql-server - 奇怪的 Entity Framework 错误 : login failed for user

asp.net - 用于跨数据库表的 LINQ to SQL。还是查看?

c# - 如何逐一生成IEnumerable的元素