【问题标题】:Retrieving matched items from an .Any() query从 .Any() 查询中检索匹配的项目
【发布时间】:2018-02-09 23:45:26
【问题描述】:

所以我有以下代码:

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;
});

现在我想检索与 .Any() 查询匹配的单个项目。如何只获得匹配的项目?

【问题讨论】:

  • 使用 Where insted of any 怎么样

标签: c# linq linq-to-objects


【解决方案1】:

您不能直接使用Any() 函数(它只返回一个bool),但.Where() 函数将返回一个过滤后的IEnumerable<T>,它也有Any() 函数。

比如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-26
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多