通过删除 foreach 循环来降低方法的复杂性

Reduce method complexity by removing foreach loops

我在 c# 中有以下代码:

foreach (var c1 in object1.Collection1)
{
    foreach (var c2 in c1.Collection2.Where(b => b.Settings?.Name != null))
    {
        foreach (var c3 in c2.Settings.Name.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => s.ToLowerInvariant().GetHashCode()).ToList())
        {
            //process c3
        }
    }
}

如何使用 linq 将我需要的元素 (c2.Settings.Name) 组合到一个数组中并且只有一个 foreach 因为使用这段代码,我的方法复杂度是 5 并且 Sonar 正在抱怨这个。

使用SelectMany扩展方法:

var query= Collection1.SelectMany(c1=>c1.Collection2
                                        .Where(b => b.Settings?.Name != null)
                                        .SelectMany(c2=>c2.Settings.Name
                                        .Where(s => !string.IsNullOrWhiteSpace(s))
                                        .Select(s => s.ToLowerInvariant().GetHashCode())));

或在 linq 查询符号中使用多个 from

var query = from c1 in Collection1
            from c2 in c1.Collection2.Where(b => b.Settings?.Name != null)
            from c3 in c2.Settings.Name.Where(s => !string.IsNullOrWhiteSpace(s))
                                       .Select(s => s.ToLowerInvariant().GetHashCode())
            select c3;