我正在尝试编写一个LINQ查询,该查询将返回两个首次登记入住且未在指定日期登记的客户列表
Cusomters
- Name (nvarchar)
- CheckInDate (datetime)
我可以编写两个单独的查询,但是可以只使用一个查询吗?
答案 0 :(得分:1)
这将根据需要返回2种客户的1个列表:
var result = Customers.GroupBy(x=>x.Name)
.Where(g=>g.Count()==1 || !g.Any(x=>x.CheckInDate == yourDate))
.SelectMany(x=>x);
如果您想要2个列表,我认为这样可行:
var result = Customers.GroupBy(x=> Customers.Count(a=>a.Name == x.Name) == 1 ? 1 : 2)
.Select(g=> g.Key == 1 ? g.ToList() : g.Where(x=>!g.Where(a=>a.CheckInDate == yourDate)
.Any(a=>a.Name == x.Name)).ToList());
//To get the customers who have first checked in
var firstCheckedIn = result[0];
//To get the customers who didn't check in on a given date
var notCheckedIn = result[1]
//or
var result = Customers.GroupBy(x=> {
var c = Customers.Where(a=>a.Name == x.Name);
return c.Count() == 1 ? 1 :
!c.Any(a=>a.CheckInDate == yourDate) ? 2 : 3;
})
.Select(g=> g.ToList()).ToList();