I find the LINQ way will look a little ugly
var assets = item.Any(a=>HaRelevantAsset(a)) ? item.Where(a => HasRelevantAsset(a)) : item.SubItems.SelectMany(item => item.Assets.Where(a => HasRelevantAsset(a)));
I would choose another option, the extension method
public static IEnumerable<Asset> SelectRelevantAssets(this Item item) { var assetsInItemFound = false; foreach (var asset in item.Assets) { if (HasRelevantAsset(asset)) { assetsInItemFound = true; yield return asset; } } if (assetsInItemFound) { yield break; } else { foreach (var subItem in item.SubItems) foreach (var asset in subItem.Assets) if (HasRelevantAsset(asset)) yield return asset; } }
At first I wanted to try the recursive call to SelectRelevantAssets, I think it would be like
if (!assetsInItemFound) { yield break; } else { foreach (var subItem in item.SubItems) foreach (var asset in SelectRelevantAssets(subItem)) yield return asset; }
But this will include the assets found in the Items collection of subItem elements
source share