删除foreach循环可以降低方法的复杂性

时间:2017-05-17 14:38:01

标签: c# linq cyclomatic-complexity

我在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且{{1抱怨这个。

1 个答案:

答案 0 :(得分:1)

使用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;