简体   繁体   English

Linq查询分组按不同

[英]Linq query group by distinct

I have a linq query which is almost complete. 我有一个接近完成的linq查询。 It's working but I need to retrieve the original list of the items in the list that fulfills the requirements. 它正在工作,但是我需要检索满足要求的列表中项目的原始列表。

Now it only returns true or false if any has the count > numberOfResourceToBook . 现在,仅当count > numberOfResourceToBook它才返回true或false。

But instead I want to return all the items in availableTimes having that (with all its properties). 但是相反,我想返回availableTimes具有该属性的所有项目(及其所有属性)。

bool enoughResourceAvailable = availableTimes.GroupBy(l => new { l.From, l.To })
  .Select(g => new
  {
      Date = g.Key,
      Count = g.Select(l => l.ResourceId).Distinct().Count()
  }).Where(c => c.Count  >= numberOfResourcesToBook).Count() > 0;

I realize this is an old question and hopefully you already figured this out long ago. 我意识到这是一个老问题,希望您早已弄清楚了。 But for someone else stumbling into this question, here is how you could solve it: 但是对于其他陷入这个问题的人来说,这是解决问题的方法:

First, you need to add the available times for each group to the anonymous objects you are selecting so you have a way to get them back after grouping. 首先,您需要将每个组的可用时间添加到您选择的匿名对象中,以便您有一种在分组后取回它们的方法。 Get rid of the .Count > 0 at the end so the result is an IEnumerable of the anonymous objects instead of a boolean. 最后消除.Count > 0 ,以便结果是匿名对象的IEnumerable而不是布尔值。

var result = availableTimes
    .GroupBy(l => new { l.From, l.To })
    .Select(g => new
    {
        Date = g.Key,
        Count = g.Select(l => l.ResourceId).Distinct().Count(),
        Times = g.Select(l => l)     // Add this to capture the times for the group
    })
    .Where(c => c.Count >= numberOfResourcesToBook);

Next, you can set the enoughResourceAvailable by using .Any() on the previous result. 接下来,您可以通过在上一个结果上使用enoughResourceAvailable .Any()来设置enoughResourceAvailable的资源。 It does the same job as .Count() > 0 except it doesn't always need to enumerate the entire list: it can return true as soon as it finds at least one item. 它执行与.Count() > 0相同的工作,不同之处.Count() > 0它并不总是需要枚举整个列表:找到至少一项就可以返回true。

bool enoughResourceAvailable = result.Any();

Lastly, to get all the times back which matched the query (if there are any), you can use SelectMany() on the result, like so: 最后,要获得与查询匹配的所有时间(如果有的话),可以对结果使用SelectMany() ,如下所示:

var allMatchingTimes = result.SelectMany(c => c.Times);

Working demo: https://dotnetfiddle.net/HCEuMR 工作演示: https//dotnetfiddle.net/HCEuMR

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM