遍历列表,执行方法:可以扩展吗?
我有一个像这样的数据结构
public class Employee
{
public string Name { get; set; }
public IEnumerable<Employee> Employees { get; private set; }
// ...
}
现在我需要循环遍历完整的结构并在每个项目上执行一个方法。
我如何为这样的遍历函数创建 IEnumerable 的扩展。
Wonderfull 会是这样的
employeList.Traverse(e => Save(e), e.Employees.Count > 0);
或者这是不可能的,我必须在我的业务逻辑中创建一个特殊的方法?
多谢。
i have a data structure like this
public class Employee
{
public string Name { get; set; }
public IEnumerable<Employee> Employees { get; private set; }
// ...
}
Now i need to loop through the complete structure and execute a method on each item.
How can i create an extension on IEnumerable for such a traverse function.
Wonderfull would be something like this
employeList.Traverse(e => Save(e), e.Employees.Count > 0);
Or is it impossible and i have to create a special method in my business logic?
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的意思是
IEnumerable
上的扩展方法吗?这当然是可行的:它必须位于静态、非泛型、非嵌套类中。
请注意,我不确定谓词位的用途...
编辑:这是我认为您正在寻找的更通用的形式:
然后您可以使用以下方式调用它:
Do you mean an extension method on
IEnumerable<Employee>
? That's certainly feasible:This has to be in a static, non-generic, non-nested class.
I'm not sure what the predicate bit is for, mind you...
EDIT: Here's the more generalised form I think you were looking for:
You'd then call it with:
我假设您的主类应该是
Employer
而不是Employee
。I'm assuming your main class should be
Employer
rather thanEmployee
.我不确定你的参数应该表示什么,但如果第二个参数是谓词,你可能想要做这样的事情:
我也可能会抛出这样的函数,在
List
List< T>
,所以ifToList
不是问题,您可以这样做I'm not sure what your parameters are supposed to signify, but if the second parameter is a predicate, you may want to do something like this:
I might also throw in that there already is such a function, on
List<T>
, so ifToList
is not an issue, you would be able to do您可以使用简单的扩展方法来做到这一点:
You can do it with a simple extension method:
虽然传递 Action 可能很有用,但它不如枚举树结构中所有项目的迭代器灵活,从而使它们可与其他 LINQ 运算符一起使用:
While passing an Action might be useful, it isn't as flexible as an iterator that enumerates all items in a tree structure, making them available for use with other LINQ operators: