LINQ中的条件选择(如果为空,则选择)
本文关键字:选择 条件 LINQ 如果 | 更新日期: 2023-09-27 18:29:45
是否有某种"LINQ"方法可以对数据进行条件选择,即如果第一个源为空,则从另一个源进行选择?一个例子是,如果您有一个项的树结构,并且您想从根中获取一些资产,或者如果它是空的,则从它的子级中获取。
我有以下例子:
IEnumerable<Item> items = ...;
// Item has a Assets property that returns IEnumerable<Asset>
// Item has a SubItems property that returns IEnumerable<Item>
// i.e. other items with assets in them
// getting assets from a "main" item
var assets = item.Assets.Where(a => HasRelevantAsset(a));
// if there were no relevant assets in the "main" item
if (!assets.Any()) {
// then reselect from "subitems" assets instead
assets = item.SubItems.SelectMany(item =>
item.Assets.Where(a => HasRelevantAsset(a)));
}
// HasRelevantAsset(Asset) is a static method that returns
// true if it is the asset that is needed
我相信LINQ方式看起来会有点难看
var assets = item.Any(a=>HaRelevantAsset(a)) ? item.Where(a => HasRelevantAsset(a)) :
item.SubItems.SelectMany(item =>
item.Assets.Where(a => HasRelevantAsset(a)));
我会选择另一种变体,扩展方法
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;
}
}
首先我想尝试对SelectRelevantAssets进行递归调用,我想会像
if (!assetsInItemFound)
{
yield break;
}
else
{
foreach (var subItem in item.SubItems)
foreach (var asset in SelectRelevantAssets(subItem))
yield return asset;
}
但这将包括在子项资产的Items集合中找到的资产