简体   繁体   中英

Linq query group by distinct

I have a linq query which is almost complete. 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 .

But instead I want to return all the items in availableTimes having that (with all its properties).

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.

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. 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.

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:

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

Working demo: https://dotnetfiddle.net/HCEuMR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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