订购IHierarchicalEnumerable List c#

时间:2015-10-29 12:18:18

标签: c# linq list

我有一个Heirarchical的菜单,例如

菜单家长A. - 子项目A. - 子项目B. 菜单父B - 子项目A. 菜单父C 菜单父D

它是从db驱动的,每个MenuParent都有一个.Order int,我想订购父项。

我的代码如下;

        List<Menu> result = (List<MenuModel>)deserializer.ReadObject(stream);
        var groupNames = result.Select(e => new Tuple<string,string,int>(e.menutitle, e.imageurl, e.ordernumber)).Distinct().ToList();

        int increment = 1;
        List<Category> lstc = new List<Category>();
        foreach (var item in groupNames)
        {
            _collection.Add(new Category(incrementforId, "0", item.Item1, item.Item2, item.Item3));
            List<string> lstItemTitle = result.Where(e => e.GroupTitle.Trim() == item.Item1).Select(x => x.ItemTitle.Trim()).Distinct().ToList();
            List<Category> lstclocal = (from ItemTitle in lstItemTitle select new Category(ItemTitle + increment, increment.ToString(), ItemTitle)).ToList();
            incrementforId++;
            lstc.AddRange(lstclocal);
        }

//ISSUE IS HERE
        _collection.GroupBy(x => x.Order);                
        _collection.AddRange(lstc);

其中;

public class CategoryCollection : List<Category>, IHierarchicalEnumerable {

但是,我似乎无法通过x.Order元素进行排序?我试过了

var _collection = _collection.GroupBy(x => x.Order);

给出了错误;

  

无法隐式转换类型   &#39;&System.Collections.Generic.IEnumerable GT;&#39;   到&#39; CategoryCollection&#39;。存在显式转换(是你   错过演员?)

我也试过.OrderBy也失败了?

我想如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您只需要替换此

//ISSUE IS HERE
_collection.GroupBy(x => x.Order);

_collection.Sort((x, y) => x.Order.CompareTo(y.Order));