我在确定如何按照输入的最新日期从数据库表中筛选出一组值时遇到问题
到目前为止,我有以下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应该返回一行。
有什么建议吗?
答案 0 :(得分:1)
如果您希望每条记录都是最新的,则可以将GroupBy
与Select
一起使用:
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();
答案 1 :(得分:0)
您需要做的是将Col2
按val分组,以便您可以选择每个分组中的最新分组。使用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();
答案 2 :(得分:0)
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();