使用递归在LINQ上过滤集合

时间:2011-11-16 15:07:14

标签: linq collections recursion filter

我有一个名为 MenuItemCollection 的集合,这个派生形式 List< MenuItem>

MenuItemCollection 有一个Singleton实例,如果我简化 MenuItem 的字段:

public class MenuItem
{
   int Id {set;get;}
   string Title {set;get;}
   MenuItemCollection ChildMenus {set;get;}
}

我需要在此集合上使用过滤器方法。例如,我想过滤一个菜单的Id的集合。 这是一个示例MenuItemCollection:

1-Home
2-User Menu
  4-Update Info
  5-Delete Account
3-News
  6-Archived News

正如您所看到的那样 Child 菜单,例如 number 4 number 6

我通常在下面使用过滤:

public List<MenuItem> Filter(MenuItemFilterArgs args)
{
     List<MenuItem> Result = new List<MenuItem>();
     IQueryable<MenuItem> QueryableTemp = this.AsQueryable();

     return (from item in QueryableTemp
                      orderby item.Ordering descending
                      select item).ToList<MenuItem>();
}

将此方法称为:

var FilteredMenus = MenuItemCollection.GetInstance.Filter(new MenuItemFilterArgs { Id = 5 });

由于 number 5 位于 number 2 menuitem下的内部集合中,结果将返回0.无法找到。

如何通过内部MenuItemCollections递归运行过滤器?你能写一个代码样本吗?

  

PS:如果你必须知道我为什么使用单例实例;我的想法是   从数据库中检索菜单并将其作为对象保存   在运行时更容易和更快地使用。

任何帮助都将受到高度赞赏。 提前致谢

1 个答案:

答案 0 :(得分:3)

这是一个工作示例。您需要ExtensionMethods.Map方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace WindowsFormsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            var menuItems1 = MenuItemCollection.Instance.Filter(null);
            var menuItems2 = MenuItemCollection.Instance.Filter(new MenuItemCriteria { Id = 5 });
            var menuItems3 = MenuItemCollection.Instance.Filter(new MenuItemCriteria { Title = "News" });
            var menuItems4 = MenuItemCollection.Instance.Filter(new MenuItemCriteria { Title = "News", IsTrash = true });
        }
    }

    public class MenuItemCollection : List<MenuItem>
    {
        public static readonly MenuItemCollection Instance;

        static MenuItemCollection()
        {
            Instance = GetMenuList();
        }

        static MenuItemCollection GetMenuList()
        {
            return new MenuItemCollection {
                new MenuItem {Id = 1, Title = "Home"},
                new MenuItem {Id = 2, Title = "User Menu", ChildMenus = new MenuItemCollection { 
                        new MenuItem { Id = 4, Title = "Update Info"},
                        new MenuItem { Id = 5, Title = "Delete"}
                    }},
                new MenuItem {Id = 3, Title = "News", ChildMenus = new MenuItemCollection { 
                        new MenuItem { Id = 6, Title = "Archived News"},
                        new MenuItem { Id = 6, Title = "Trashy News", IsTrash = true}
                    }},
            };
        }

        public List<MenuItem> Filter(MenuItemCriteria criteria)
        {
            var expression = PredicateBuilder.True<MenuItem>();

            if(criteria != null)
            {
                if (criteria.Id.HasValue)
                {
                    expression = expression.And(menuItem => menuItem.Id == criteria.Id);
                }

                if (!string.IsNullOrEmpty(criteria.Title))
                {
                    expression = expression.And(menuItem => menuItem.Title.Contains(criteria.Title));
                }

                if (criteria.IsTrash.HasValue)
                {
                    expression = expression.And(menuItem => menuItem.IsTrash == criteria.IsTrash);
                }
            }

            Func<MenuItem, bool> searchCriteria = expression.Compile();
            Func<MenuItem, IEnumerable<MenuItem>> childrenSelector = x => x.ChildMenus;

            return this.Map(searchCriteria, childrenSelector).ToList();
        }
    }

    public class MenuItemCriteria
    {
        public int? Id { set; get; }
        public string Title { set; get; }
        public bool? IsTrash { set; get; }
    }

    public class MenuItem
    {
        public int Id { set; get; }
        public string Title { set; get; }
        public bool IsTrash { set; get; }
        public MenuItemCollection ChildMenus { set; get; }
    }

    public static class ExtensionMethods
    {
        public static IEnumerable<T> Map<T>(this IEnumerable<T> source,
                                            Func<T, bool> selector = null,
                                            Func<T, IEnumerable<T>> childrenSelector = null)
        {
            if (source == null) return new List<T>();

            if (selector == null)
            {
                // create a default selector that selects all items
                selector = x => true;
            }

            var list = source.Where(selector);

            if (childrenSelector != null)
            {
                foreach (var item in source)
                {
                    list = list.Concat(childrenSelector(item).Map(selector, childrenSelector));
                }
            }

            return list;
        }
    }

    public static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                             Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }
    }
}