Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order list by parent and child items

Tags:

c#

.net

linq

I have a list of products that have to be ordered by parent then all children of that parent, then next parent, etc.

Product One
    Child One
    Child Two
Product Two
    Child One

These products are all in one table with a parent id field, the child products have a parent id but the parent items can have a null parent (indicating that product is a top level product)

Sample table

I was thinking something like the following:

var list = GetProductList();
var newList = new List<ProductDTO>();

var parents = from p in list
    where p.Parent == null
    select p.Id;


foreach (var parent in parents)
{
    var tempList = new List<ProductDTO>();
    tempList.Add(list.FirstOrDefault(x => x.Id == parent));
    tempList.AddRange(list.Where(x => x.Parent == parent).OrderBy(x => x.Id));
    newList.AddRange(tempList);
}

Any suggestions on how I would do this a little cleaner?

like image 951
crunchy Avatar asked Feb 27 '14 15:02

crunchy


2 Answers

you could try something like that. Assuming parent is a nullable:

var sorted = list.OrderBy(x => x.parent ?? x.id).ThenBy(x=>x.id);

if its a string:

            var sorted = list.OrderBy(x =>
            {
                if (x.parent == "null")
                    return x.id;
                else
                    return Convert.ToInt32(x.parent);
            }).ThenBy(x => x.id);
like image 146
Lev Avatar answered Nov 09 '22 19:11

Lev


Given "Parent" is nullable property (assuming nullable int here). Following should give you parent-child related ordered list:

 public class ProductDTO
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public int? Parent { get; set; }
 }

 var products = new List<ProductDTO>();
 products.Add(new ProductDTO() { Id = 1, Name = "Product One" });
 products.Add(new ProductDTO() { Id = 2, Name = "Product Two" });
 products.Add(new ProductDTO() { Id = 3, Name = "Product Three" });
 products.Add(new ProductDTO() { Id = 4, Name = "Child One", Parent=1 });
 products.Add(new ProductDTO() { Id = 5, Name = "Child Two", Parent = 2 });
 products.Add(new ProductDTO() { Id = 6, Name = "Child One", Parent = 1 });

var ordered = products
                .Where(p => p.Parent == null)
                .OrderBy(p=> p.Id)
                .Select(p => products
                    .Where(c => c.Parent == p.Id)
                    .OrderBy(c => c.Id))
                .ToList();
like image 4
loopedcode Avatar answered Nov 09 '22 20:11

loopedcode