0

I have A list

key ParentKey
1   Null
2   1
3   Null
4   Null
5   1
6   4
7   6
8   3

I want it sorted in

key ParentKey
1   Null
2   1
5   1
3   Null
8   3
4   Null
6   4
7   6

via linq how can this be done? Any help is most wellcome

Omar
  • 16,329
  • 10
  • 48
  • 66
Taufiq Abdur Rahman
  • 1,348
  • 4
  • 24
  • 44

3 Answers3

1

Assuming that the result should be:

key ParentKey
1   Null
2   1
5   1
3   Null
8   3
4   Null
6   4
7   6

I can say that you can't do anything if there isn't a logic that make the null values in that position into the list.

So using Linq you can order the list using the OrderBy() function:

list = list.OrderBy(x => x.ParentKey).ToList();

But using this function the result is the following:

key ParentKey
1   Null
3   Null
4   Null
2   1
5   1
8   3
6   4
7   6
Omar
  • 16,329
  • 10
  • 48
  • 66
1

if you have a list of

public class MyObject{
      int Key {get;set;}
      int ? ParentKey{get;set;}
}

then for sorting this list use :

 var list = new List<MyObject>(){ new MyObject{ Key = 1 , ParentKey = null } , new MyObject{Key=2 , PatentKey = 1}  /* and so on */};

  var sortedList = list.OrderBy(o=>o.ParentKey , new MyComparer());



public class MyComparer : IComparer<MyObject>
{     
    public int Compare(MyObject o1, MyObject o2)
    {
        if (ol.HasValue && o2.HasValue)
        {
            if (ol.ParentKey.Value == o2.ParentKey.Value)
                 return 0;
            return ol.ParentKey.Value  > o2.ParentKey.Value  ? 1 : -1;
        }
        else
            return 0;

    }
}

this will generate exact your expecting sequence

Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63
0

I believe what you want to achieve here is a DFS ordered print of a tree.
Linq can't help you with that (at least out of the box).

I'd suggest adapting a DFS implementation to your data structure. See Eric Lippert's suggestion.

Community
  • 1
  • 1
seldary
  • 6,186
  • 4
  • 40
  • 55