我在找出如何根据输入的最新日期从数据库表中过滤一组值时遇到了问题
到目前为止,我有以下linq语句
List<int> vals = new List<int>{1, 2, 3, 4, 5};
Context.Table.Where(x => x.Col1 == col1 && vals.Contains(x.Col2)).OrderByDescending(x => x.DateEntered).Distinct().ToList();
它似乎只是返回所有行?因此,基本上对于每个vals
项,例如1、2、3、4,它应该返回一行。
有什么建议吗?
发布于 2018-08-29 02:40:50
如果需要每条记录的最新信息,可以使用带有Select
的GroupBy
Context.Table
.Where(x => x.Col1 == col1 && vals.Contains(x.Col2))
.GroupBy(x => x.Col2)
// order by descending on the group
// and then take the first
.Select(grp => grp.OrderByDescending(x => x.DateEntered).First())
.ToList();
发布于 2018-08-29 03:28:56
您需要做的是按Col2
分组,这样您就可以选择每个组中的最新组。使用LINQ Lambda语法:
List<int> vals = new List<int>{1, 2, 3, 4, 5};
var ans = Context.Table.Where(x => x.Col1 == Col1 && vals.Contains(x.Col2))
.GroupBy(x => x.Col2)
.Select(xg => xg.OrderByDescending(x => x.DateEntered).First())
.ToList();
发布于 2020-02-05 14:52:20
var checkIn = iclock_transaction
.Where(x => x.punch_state == "0" )
// .AsEnumerable()
.GroupBy(x=>new { x.emp_code,x.punch_time.Date })
// order by descending on the group
// and then take the first
.Select(grp => grp.OrderBy(x => x.punch_time).First())
.ToList();
//********* Perfectly work with check out ********
var checkOut = iclock_transaction
.Where(x => x.punch_state == "1")
// .AsEnumerable()
.GroupBy(x => x.emp_code)
// order by descending on the group
// and then take the first
.Select(grp => grp.OrderByDescending(x => x.punch_time).First())
.ToList();
iclock_transaction = checkIn.Concat(checkOut).ToList();
https://stackoverflow.com/questions/52064261
复制相似问题