Retrieving matched items from an .Any() query

66 Views Asked by At

So I have the following code:

var itemsGrouped = this.Errors.GroupBy(x => x.UniqueName).AsEnumerable();
var hasErrors = !itemsGrouped.Any((f) =>
{
    var errorCount = f.ToArray()
    .Where(x => x.ErrorCount.HasValue)
    .Count(x => x.ErrorCount.Value > 0);

    return errorCount > 2;
});

and now I want to retrieve the individual items that matched the .Any() query. How do I get only matching items?

1

There are 1 best solutions below

0
On BEST ANSWER

You can't directly, using the Any() function (it just returns a bool), but the .Where() function will return a filtered IEnumerable<T> which also has the Any() function.

So something like:

var itemsGrouped = this.Errors.GroupBy(x => x.UniqueName).AsEnumerable();
var invalidItems = itemsGrouped.Where((f) =>
{
    var errorCount = f.ToArray()
    .Where(x => x.ErrorCount.HasValue)
    .Count(x => x.ErrorCount.Value > 0);

    return errorCount > 2;
});

var hasErrors = !invalidItems.Any();

//Do stuff with invalidItems