我有一个课程如下
public class Material
{
public string `MaterialName` { get; set; }
public List<Material> `ChildMaterial` { get; set; }
}
我使用上面的类创建了一个嵌套列表,如下例所示
材料J
材料2
我想要一些linq查询某些方法,它会过滤掉材料D ,并会给我直到根的路径并删除它下面的所有节点。如下例所示,材料D 可以在树中的任何级别找到,并且可以重复。
答案 0 :(得分:0)
首先,您需要一个能够展平这种树结构的LINQ方法,以便您能够遍历所有可用节点:
public static IEnumerable<TSource> Map<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selectorFunction,
Func<TSource, IEnumerable<TSource>> getChildrenFunction)
{
if (source == null)
throw new ArgumentNullException("source");
if (selectorFunction == null)
throw new ArgumentNullException("selectorFunction");
if (getChildrenFunction == null)
throw new ArgumentNullException("getChildrenFunction");
return MapImpl(source, selectorFunction, getChildrenFunction);
}
private static IEnumerable<TSource> MapImpl<TSource>(
IEnumerable<TSource> source,
Func<TSource, bool> selectorFunction,
Func<TSource, IEnumerable<TSource>> getChildrenFunction)
{
// Go through the input enumerable looking for children,
// and add those if we have them
foreach (TSource element in source)
{
foreach (var childElement in MapImpl(getChildrenFunction(element), selectorFunction, getChildrenFunction))
{
yield return childElement;
}
if (selectorFunction(element))
yield return element;
}
}
通过此操作,您现在可以浏览主列表并找到所有需要的节点:
var matchingMaterials = MyMaterials.Map(material => true, material => material, material => material.ChildMeterials)
.Where(material => material.Name = "Material D")
// Materialization is needed, cause manipulation is desired while iterating over the result.
.ToList();
然后你想以某种方式操纵这些节点(例如从匹配的节点中删除所有子节点):
foreach(var material in matchingMaterials)
{
material.ChildMaterials.Clear();
}