我正在LINQ中寻找一种方法来匹配下面的SQL查询。
Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number
真的在这件事上寻求帮助。由于Group By
语法,上面的查询获取每个序列号的最大uid。
using (DataContext dc = new DataContext())
{
var q = from t in dc.TableTests
group t by t.SerialNumber
into g
select new
{
SerialNumber = g.Key,
uid = (from t2 in g select t2.uid).Max()
};
}
var q = from s in db.Serials
group s by s.Serial_Number into g
select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }
在方法链形式中:
db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
{
Serial_Number = g.Key,
uid = g.Max(row => row.uid)
});
我已经在LinqPad中检查了DamienG的答案。代替
g.Group.Max(s => s.uid)
应该是
g.Max(s => s.uid)
谢谢!
如果只需要这两个字段,答案是可以的,但对于更复杂的对象,这种方法可能很有用:
from x in db.Serials
group x by x.Serial_Number into g
orderby g.Key
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()
这将避免"选择新的"
这可以在LINQλ表达式中使用GroupBy和SelectMany来完成
var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));
基于以上内容,我想将每组中的最佳结果放入与原始列表相同类型的列表中:
var bests = from x in origRecords
group x by x.EventDescriptionGenderView into g
orderby g.Key
select g.OrderByDescending(z => z.AgeGrade)
.FirstOrDefault();
List<MasterRecordResultClaim> records = new
List<MasterRecordResultClaim>();
foreach (var bestresult in bests)
{
records.Add(bestresult);
}
EventDescriptionGenderView是将几个字段合并到一个字符串中。这将为每个活动选择最佳年龄等级。