繁体   English   中英

如何在Linq查询中使用模型属性?

[英]How can I use my model properties in a Linq query?

我有这个linq查询

var sales=db.Customers
    .GroupBy
    .Select(c=> new MyModel
     {
        count1=c.where(someCondition).Count(),
        count2=c.where(otherCondition).Count(), 
        finalCount=count2-count1
     });

在linq有可能吗? 我该如何解决这个问题?

不,但是您可以使用匿名块:

var sales=db.Customers.GroupBy(...).Select{c=> 
{ 
    int count1 = c.Count(condition1);
    int count2 = c.Count(condition2);

    return new MyModel{
        count1=count1,
        count2=count2,
        finalCount= count2 - count1
    }
});

您可以先选择一个匿名类型,然后将其投影到第二个Select

var sales = db.Customers
    .GroupBy( ... )
    .Select(g => new
    {
        count1 = g.Where( condition ).Count(),  
        count2 = g.Where( condition ).Count()
    })
    .Select{x => new MyModel
     {
        count1 = x.count1,
        count2 = x.count2, 
        finalCount = x.count2 - x.count1 
     });

如果我理解正确,请将代码放在属性初始化程序之后:

var sales=db.Customers.GroupBy(...).Select(c => 
{
    var model new MyModel{
        count1=c.Count(),
        count2=c.Count()
    } 
    model.finalCount = model.count1 - model.count2

    return model;
});

但是在这种情况下,我只想在MyModel类上创建一个只读属性:

public class MyModel
{
   public int FinalCount => count1 - count2;
}

然后仅初始化必填字段:

var sales=db.Customers.GroupBy(...).Select(c => new MyModel
{
   count1=c.Count(),
   count2=c.Count()
});

FinalCount将自动为您计算。

您也可以使用let子句执行此操作:

var sales=from c in db.Customers
          group c by c.SomeColumn into g
          let Count1= =g.Count(someCondition)
          let Count2=g.Count(otherCondition)
          select new MyModel
                 {
                   count1=Count1,
                   count2=Count2, 
                   finalCount=Count1-Count2
                 };

使用方法的语法相同:

var sales=db.Customers
    .GroupBy(c=>c.SomeColumn)
    .Select(g=>new
     {
        Count1=g.Count(someCondition),
        Count2=g.Count(otherCondition)
     })
    .Select(c=> new MyModel
     {
        count1=c.Count1,
        count2=c.Count2, 
        finalCount=c.Count1-c.Count2
     });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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