使用相同的过滤器选择多个子列

时间:2015-09-30 17:23:10

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

我有这个Linq lambda表达式,它会生成异常复杂的SQL select to database。是否有可能简化它?

var devices = db.Devices
                        .Where(a => a.active == true)
                        .Select(a => new DeviceToDisplay
                        {
                            Id = a.Id,
                            serialNumber = a.serialNumber,                               
                            deviceRegion = a.deviceRegion,
                            activeIP = a.IPaddresses.Where(b => b.active == true).Select(b => b.IPaddress1).FirstOrDefault(),
                            Wip = a.IPaddresses.Where(b => b.active == true).Select(b => b.W_IP).FirstOrDefault(),
                            Sip = a.IPaddresses.Where(b => b.active == true).Select(b => b.S_IP).FirstOrDefault(),
                            model = a.SPdatas.Where(c => c.model != "").OrderByDescending(c => c.collectionDate).Select(c => c.model).FirstOrDefault(),
                            firmware = a.SPdatas.Where(c => c.model != "").OrderByDescending(c => c.collectionDate).Select(c => c.firmware).FirstOrDefault(),                               
                            lastMPteamActivity = a.activityLogs.OrderByDescending(c => c.updatedDate).Select(c => c.updatedDate).FirstOrDefault(),                               
                            country = a.MPPinformations.Select(c => c.country).FirstOrDefault()                                
                        });

2 个答案:

答案 0 :(得分:2)

首先,您的linq查询看起来非常复杂。想象一下如何通过编写SQL查询来实现这一点。

建议:你写的是:

 a.IPaddresses.Where(b => b.active == true).

  a.SPdatas.Where(c => c.model != "").OrderByDescending(c => c.collectionDate).

在多个地方。

相反,你可以创建一个匿名类型。例如,

var foo = from x in sb.Devices.Where(a=> a.active)
          select new { Id = x.ID, 
                       IPAddress = a.IPaddresses.Where(b => b.active), ... }

然后,您可以使用foo创建您的Devices对象。

答案 1 :(得分:2)

看看这是否更好:

var devices = db.Devices
  .Where(a => a.active == true)
  .Select(a => new DeviceToDisplay {
    Id = a.Id,
    serialNumber = a.serialNumber,                               
    deviceRegion = a.deviceRegion,
    activeIP = a.IPaddresses.Where(b => b.active == true).FirstOrDefault(),
    SPdata = a.SPdatas.Where(c => c.model != "").OrderByDescending(c => c.collectionDate).FirstOrDefault(),
    lastMPteamActivity = a.activityLogs.OrderByDescending(c => c.updatedDate).Select(c => c.updatedDate).FirstOrDefault(),                               
    country = a.MPPinformations.Select(c => c.country).FirstOrDefault()                                
})
  .Select(a=> new DeviceToDisplay {
    Id=a.Id,
    serialNumber=a.serialNumber,
    deviceRegion=a.deviceRegion,
    activeIP=a.activeIP.IPaddress1,
    Wip=a.activeIP.W_IP,
    Sip=a.activeIP.S_IP,
    model=a.SPdata.model,
    firmware=a.SPdata.firmware,
    lastMPteamActivity=a.lastMPteamActivity,
    country=a.county
});