Search code examples
c#entity-frameworksortinglinq-to-entitiesself-referencing-table

sorting Self-Referencing Relationship


Assume the following model. Note the self-referencing relationship "parent".

 public class Category 
    {
        public virtual long Id { get; set; }
        public virtual string Name { get; set; }
        public virtual Category Parent { get; set; }
        public virtual long? ParentId { get; set; }
    }

My data are as follows:

id   |    name   |  parentId
1--------tag 1 ----- null
2--------tag 2 ----- 1
3--------tag 3 ----- 1
4--------tag 4 ----- 2
5--------tag 5 ----- null
6--------tag 6 ----- null

I want to write a query that data will be sorted as follows

tag 1
----->tag 2
----->----->tag 4
----->tag 3
tag 5
tag 6

This is my code

var categorys = __categories
                .AsNoTracking()
                .ToList();

I do not know how to sort them


Solution

  • Try this recursive function

      class Program
    {
        static void Main(string[] args)
        {
            using (var db = new aaContext2())
            {
                Temp temp = new Temp();
    
                var cc = db.Catagory.FirstOrDefault();
                IList<Category> parentList =new List <Category>();
                foreach (Category catagory in db.Catagory.Where(cat => cat.ParentId == null))
                {
                    parentList.Add(temp.Recursive(catagory.Id, catagory.Name));
                }
            }
        }
    }
    public class Temp{
        public Category Recursive(long parentId, string name)
        {
            Category catagory = new Category();
            catagory.Id = parentId; catagory.Name = name;
            using (var db = new aaContext2())
            {
                //base condition
                if (db.Catagory.Where(catagory1 => catagory1.ParentId == parentId).Count() < 1)
                {
                    return catagory;
                }
                else
                {
                    IList<Category> newCatagoryList = new List<Category>();
                    foreach (Category cat in db.Catagory.Where(cata => cata.ParentId == parentId))
                    {
                        newCatagoryList.Add(Recursive(cat.Id, cat.Name));
                    }
                    catagory.CatagoryList = newCatagoryList;
                    return catagory;
                }
            }
        }
    }
    public class aaContext2 : DbContext
    {
        public DbSet<Category> Catagory { get; set; }
    }
    public class Category
    {
        public virtual long Id { get; set; }
        public virtual string Name { get; set; }
        public virtual Category Parent { get; set; }
    
        public virtual ICollection<Category> CatagoryList { get; set; }
        public virtual long? ParentId { get; set; }
    }