我在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抱怨这个。
答案 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;