0

我试图弄清楚如何编写一个 LINQ 查询,该查询将返回两个第一次签到和在给定日期未签到的客户列表

Cusomters
- Name (nvarchar)
- CheckInDate (datetime)

我可以编写两个单独的查询,但是否可以只使用一个查询?

4

1 回答 1

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();
于 2013-08-15T23:42:03.020 回答