我如何编写LINQ查询来执行以下操作?
我有一个数据库表,其架构如下:
ID - Int
Time - DateTime
RecordType - Int
Msg - String
我想为每个'RecordType'
获取最新的(使用'Time'字段)记录另一个限制是我只对某些RecordTypes感兴趣 - 包含在int数组中的那些。
查询结果将是每个RecordType一条记录 - 此类型的最新记录。
答案 0 :(得分:2)
var results = source.GroupBy(x => x.RecordType)
.Where(g => myRecordTypes.Contains(g.Key))
.Select(g => g.OrderByDescending(x => x.Time).First())
.ToList();
myRecordTypes
为int[]
,其中包含您希望得到的一组RecordType
。
result
将List<Record>
每个RecordType
一个项目。
您可以将其更改为例如Dictionary<int, Recort>
RecordType
:
var results = source.GroupBy(x => x.RecordType)
.Where(g => myRecordTypes.Contains(g.Key))
.Select(g => new { g.Key, item = g.OrderByDescending(x => x.Time).First() })
.ToDictionary(x => x.Key, x => x.item);
答案 1 :(得分:0)
按记录类型对它们进行分组,过滤掉您想要的那些,然后选择按时间排序的该组中的第一个项目。
int[] recordTypes = GetRecordTypes();
var query = context.Table.GroupBy(item => item.RecordType)
.Where(group => recordTypes.Contains(group.Key))
.Select(group => group.OrderBy(item => item.Time).FirstOrDefault());