Enumerating Collections that are not inherently IEnumerable?

后端 未结 5 1618
予麋鹿
予麋鹿 2020-11-29 03:45

When you want to recursively enumerate a hierarchical object, selecting some elements based on some criteria, there are numerous examples of techniques like \"flattening\" a

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 04:20

    Based on mrydengren's solution:

    public static IEnumerable GetRecursively(this IEnumerable collection,
        Func selector,
        Func predicate)
    {
        foreach (var item in collection.OfType())
        {
            if(!predicate(item)) continue;
    
            yield return item;
    
            IEnumerable children = selector(item).GetRecursively(selector, predicate);
            foreach (var child in children)
            {
                yield return child;
            }
        }
    }
    
    
    var theNodes = treeView1.Nodes.GetRecursively(
        x => x.Nodes,
        n => n.Text.Contains("1")).ToList();
    

    Edit: for BillW

提交回复
热议问题