gpt4 book ai didi

c# - 使用 linq 过滤分层列表

转载 作者:太空狗 更新时间:2023-10-30 01:22:44 25 4
gpt4 key购买 nike

这是我的产品模型

public class Product
{
public string Name{ get; set; }

public int ProductNumber{ get; set; }

public List<Product> ProductList { get; set; }
}

//// below is the structure of the list
IList<Product> rootList = new List<Product>
{
new Product
{
ProductNumber = 1, Name = "A",
ProductList = new List<Product> { new Product { ProductNumber = 2, Name = "A1",
ProductList = new List<Product> { new Product { ProductNumber = 3, Name = "A2", ProductList = new List<Product>()} }}
}
},

new Product
{
ProductNumber = 4, Name = "B",
ProductList = new List<Product> { new Product { ProductNumber = 5, Name = "B1",
ProductList = new List<Product> { new Product { ProductNumber = 6, Name = "B2", ProductList = new List<Product>()} }}
}
},

new Product
{
ProductNumber = 7, Name = "C",
ProductList = new List<Product> { new Product { ProductNumber = 8, Name = "C1",
ProductList = new List<Product> { new Product { ProductNumber = 9, Name = "C2", ProductList = new List<Product>()} }}
}
}
};

我需要过滤上面包含小于 5 的 ProductNumber 的列表,即。预期输出是产品编号小于 5 的产品列表。

有可用的扩展吗?请帮忙。

这是我的预期结果

            Product 
{
ProductNumber : 1,
Name : "A",
ProductList : { {
ProductNumber : 2,
Name : "A1",
ProductList :{ {
ProductNumber = 3,
Name : "A2",
ProductList : null} }}
}
},

Product
{
ProductNumber : 4,
Name : "B"
ProductList : null
}

最佳答案

将类似“flatten-this-tree”的 LINQ 函数组合在一起相当容易

public static IEnumerable<T> Flatten<T>(
this IEnumerable<T> source,
Func<T, IEnumerable<T>> childSelector)
{
HashSet<T> added = new HashSet<T>();
Queue<T> queue = new Queue<T>();
foreach(T t in source)
if (added.Add(t))
queue.Enqueue(t);
while (queue.Count > 0)
{
T current = queue.Dequeue();
yield return current;
if (current != null)
{
IEnumerable<T> children = childSelector(current);
if (children != null)
foreach(T t in childSelector(current))
if (added.Add(t))
queue.Enqueue(t);
}
}
}

然后您可以在常规 LINQ 中使用它,例如

var lessThanFive = rootList
.Flatten(p => p.ProductList)
.Where(p => p.ProductNumber < 5)
.ToList();

编辑:从您的编辑中我可以看出这不是您想要的。 (您不需要产品列表,您想要产品树...)我将把它留在这里,因为我非常喜欢它作为我认为您的问题的解决方案是,但我也会考虑你的新问题......

编辑:如果您不介意修改原始对象,您可以按如下方式使用它:

rootList = rootList.Where(p => p.ProductNumber < 5).ToList();
foreach (var pr in rootList.Flatten(p => p.ProductList))
pr.ProductList = pr.ProductList.Where(p => p.ProductNumber < 5).ToList();

关于c# - 使用 linq 过滤分层列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12957567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com