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

时间:2016-04-14 14:08:05

标签: c# linq

我有这个linq查询

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

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

4 个答案:

答案 0 :(得分:4)

不,但您可以使用匿名阻止:

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

答案 1 :(得分:3)

您可以先选择投射到第二个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 
     });

答案 2 :(得分:1)

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

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将自动为您计算。

答案 3 :(得分:1)

您也可以使用 try { string strXML = File.ReadAllText("xml.xml"); XDocument xsrcdoc = XDocument.Parse(strXML); var KeyValuePairs = (from xml in xsrcdoc.Descendants("add") select new { Key = xml.Attribute("key").Value, value = xml.Attribute("value").Value }).ToList(); } //Put a break-point here and mouse-over KeyValuePairs and you should see your values.... catch (Exception) { throw; } 子句执行此操作:

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