2011-01-07 57 views
0

的最小值我有以下的列LINQ查询发现一列

inspection_dt, 
contact_dt, 
description, 
product_mod, 
product_desc, 
contact_nm, 
history_id, 
inspect_id, 
history_type, 
incident_product_id, 
contact_history_id 

我会使用LINQ从该表中查询行的泛型列表的表。我想要的是history_id的最小值(MIN) - 并且模仿这个SQL查询。

SELECT DISTINCT 
    inspection_dt, 
    contact_dt, 
    description, 
    product_mod, 
    product_desc, 
    contact_nm, 
    MIN(history_id) AS history_id, 
    inspect_id, 
    history_type, 
    incident_product_id, 
    contact_history_id 
FROM 
    myTable 
GROUP BY 
    inspection_dt, 
    contact_dt, 
    description, 
    product_mod, 
    product_desc, 
    contact_nm, 
    inspect_id, 
    history_type, 
    incident_product_id, 
    contact_history_id 

我已经试过像片段

var searchData = items 
    .GroupBy(i => new { i.history_id }) 
    .Select(g => new { history = g.Min() }) 
    .Distinct(); 

但仍得到全乱了

我开始使用像MIN,MAX等功能卡,并在LINQ分组并希望任何帮助我可以得到。

谢谢,

回答

3

如果要完全模仿的查询,可以通过你在你的SQL分组由同一列或字段需要组。尝试像

.GroupBy(item => 
     new 
     { 
      item.inspection_dt, 
      item.contact_dt, 
      item.description, 
      item.product_mod, 
      item.product_desc, 
      item.contact_nm, 
      item.inspect_id, 
      item.history_type, 
      item.incident_product_id 
     } 
    ) 
.Select(g => g.Min(item => item.history_id)) 
1

你可以试试下面的代码。

我注意到,当我在Profiler中查看它时,它会生成一个SQL交叉连接,但我认为它可以实现你想要的功能,而且你可能可以对它进行更多的调整。

var searchData = items.Select(x => new {x.inspection_dt,x.contact_dt, history= items.Min(j => j.history_id)}).Distinct(); 

希望这有助于