遍历列表,执行一个方法:扩展可能吗?

时间:2010-07-19 13:40:20

标签: c# .net linq .net-3.5 lambda

我有这样的数据结构

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);

或者它是不可能的,我必须在我的业务逻辑中创建一个特殊的方法?

非常感谢。

5 个答案:

答案 0 :(得分:6)

您的意思是IEnumerable<Employee>上的扩展方法吗?这当然是可行的:

public static void Traverse(this IEnumerable<Employee> employees,
                            Action<Employee> action,
                            Func<Employee, bool> predicate)
{
    foreach (Employee employee in employees)
    {
        action(employee);
        // Recurse down to each employee's employees, etc.
        employee.Employees.Traverse(action, predicate);
    }
}

这必须是一个静态的,非泛型的,非嵌套的类。

我不确定谓词位是什么,请注意......

编辑:这是我认为您正在寻找的更通用的形式:

public static void Traverse<T>(this IEnumerable<T> items,
                               Action<T> action,
                               Func<T, IEnumerable<T>> childrenProvider)
{
    foreach (T item in items)
    {
        action(item);
        Traverse<T>(childrenProvider(item), action, childrenProvider);
    }
}

然后你用:

来调用它
employees.Traverse(e => Save(e), e => e.Employees);

答案 1 :(得分:2)

我假设你的主要课程应该是Employer而不是Employee

public static class EmployerExtensions
{
    public static void Traverse(this Employer employer, Action<Employee> action)
    {
        // check employer and action for null and throw if they are

        foreach (var employee in employer.Employees)
        {
            action(employee);
        }
    }
}

答案 2 :(得分:0)

我不确定你的参数应该表示什么,但如果第二个参数是谓词,你可能想要这样做:

public static void Traverse(this IEnumerable<T> source, Action<T> action, Func<T,bool> predicate) {
   foreach(T item in source.Where(predicate)) {
      action.Invoke(item);
   }
}

我可能也会在List<T>已经存在这样的功能,所以如果 ToList不是问题,那么你就能做到

employeList.Where(e => e.Employees.Count > 0).ToList().ForEach(Save);

答案 3 :(得分:0)

您可以使用简单的扩展方法执行此操作:

employeeList.ForEach(e => Save(e));

public static partial class IEnumerableExtensions
{
    /// <summary>
    /// Executes an <see cref="Action&lt;T&gt;"/> on each item in a sequence.
    /// </summary>
    /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam>
    /// <param name="source">An <see cref="IEnumerable&lt;T&gt;"/> in which each item should be processed.</param>
    /// <param name="action">The <see cref="Action&lt;T&gt;"/> to be performed on each item in the sequence.</param>
    public static void ForEach<T>(
        this IEnumerable<T> source,
        Action<T> action
        )
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (action == null)
            throw new ArgumentNullException("action");

        foreach (T item in source)
            action(item);
    }
}

答案 4 :(得分:0)

传递Action可能很有用,但它不像枚举树结构中的所有项的迭代器那样灵活,使它们可以与其他LINQ运算符一起使用:

public static class ExtensionMethods
{
    // Enumerate all descendants of the argument,
    // but not the argument itself:

    public static IEnumerable<T> Traverse<T>( this T item, 
                                     Func<T, IEnumerable<T>> selector )
    {
        return Traverse<T>( selector( item ), selector );
    }

    // Enumerate each item in the argument and all descendants:

    public static IEnumerable<T> Traverse<T>( this IEnumerable<T> items, 
                                        Func<T, IEnumerable<T>> selector )
    {
        if( items != null )
        {
            foreach( T item in items )
            {
                yield return item;
                foreach( T child in Traverse<T>( selector( item ), selector ) )
                    yield return child;
            }
        }
    }
}           

// Example using System.Windows.Forms.TreeNode:

TreeNode root = myTreeView.Nodes[0];

foreach( string text in root.Traverse( n => n.Nodes ).Select( n => n.Text ) )
   Console.WriteLine( text );

// Sometimes we also need to enumerate parent nodes
//
// This method enumerates the items in any "implied"
// sequence, where each item can be used to deduce the
// next item in the sequence (items must be class types
// and the selector returns null to signal the end of
// the sequence):

public static IEnumerable<T> Walk<T>( this T start, Func<T, T> selector )
    where T: class
{
    return Walk<T>( start, true, selector )
}

// if withStart is true, the start argument is the 
// first enumerated item in the sequence, otherwise 
// the start argument item is not enumerated:

public static IEnumerable<T> Walk<T>( this T start, 
                                      bool withStart, 
                                      Func<T, T> selector )
    where T: class
{
    if( start == null )
        throw new ArgumentNullException( "start" );
    if( selector == null )
        throw new ArgumentNullException( "selector" );

    T item = withStart ? start : selector( start );
    while( item != null )
    {
        yield return item;
        item = selector( item );
    }
}

// Example: Generate a "breadcrumb bar"-style string
// showing the path to the currently selected TreeNode
// e.g., "Parent > Child > Grandchild":

TreeNode node = myTreeView.SelectedNode;

var text = node.Walk( n => n.Parent ).Select( n => n.Text );

string breadcrumbText = string.Join( " > ", text.Reverse() );