Как заказать по 2 поля с отношением ребенок / родитель. Сортировать так, чтобы дочерние элементы следовали за своими родителями в отсортированном списке? - PullRequest
0 голосов
/ 07 октября 2019

Я запрос в таблице, как показано ниже.

Id
BeforeId
Description

Например:

Id        BeforeId       Description
1         NULL           test
2         NULL           test1
3         2              test2
4         3              test3

Если BeforeId не равен нулю, будет выдвигаться перед Id. Я хотел бы заказать по Id и BeforeId с сортировкой в ​​следующем порядке.

Id        BeforeId       Description
1         NULL           test
4         3              test3
3         2              test2
2         NULL           test1

Я пытаюсь код, как показано ниже, но это не так.

var listOrder = _entites.Orders.OrderBy(t => t, new CustomComparer()).ToList();

 public class CustomComparer : IComparer<Order>
{
    public int Compare(Order lotA, Order lotB)
    {
        if (lotA.BeforeId!=null)
        {
            if (lotB.Id == lotA.BeforeId)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
        else if(lotB.BeforeId != null )
        {
            if(lotA.Id == lotB.BeforeId)
            {
                return 1; // A > B
            }
            else
            {
                return 0;
            }

        }
        else
        {
            return 0;
        }
    }
}

Может кто-нибудь сказать мнеКак решить эту проблему.

Спасибо!

1 Ответ

0 голосов
/ 15 октября 2019

Первый я создаю модель представления (добавить столбец Seq) и сортирую ее так:

Id        BeforeId       Description   Seq
1         NULL           test           1
2         NULL           test1          2
3         2              test2          3
4         3              test3          4

Я автоматически сгенерирую порядковый номер. После этого я обновлю seq, найдя каждый элемент перед id, чтобы снова отсортировать список. С большими данными это может занять много времени.

//list order need to sort
var listNeedToSort = _entites.Order.ToList();
//list order have before id
var listBeforeId = listNeedToSort.Where(p=>p.BeforeId!=null).Select(p => p.BeforeId).ToList();
 //count number of duplicate data is not process
 int countLoopDuplicateButNotProcess = 0;

  while (listBeforeId.Any())
                {
                    foreach (var item in listNeedToSort.OrderByDescending(p => p.BeforeId))
                    {
                        if (item.BeforeId != null)
                        {
                            //get record which is mentioned by other record through beforeid.
                            var recordSummary = listNeedToSort.FirstOrDefault(p => p.Id == item.BeforeId);

                            if (recordSummary != null)
                            {
                                // if sequence number of item with before id greater than record which has id equals beforeid
                                if (item.Seq > recordSummary.Seq)
                                {
                                    //reset count loop but it process again
                                    countLoopDuplicateButNotProcess = 0;
                                    item.Seq = recordSummary.Seq;
                                    //sort again list
                                    foreach (var item1 in listNeedToSort.Where(p => p.Seq >= recordSummary.Seq && p.Id != item.Id).OrderBy(p => p.Seq))
                                    {
                                        item1.Seq += 1;
                                    }
                                    //remove beforeid in listBeforeId
                                    listBeforeId.Remove(item.BeforeId);
                                }
                                else
                                {
                                    //not process
                                    countLoopDuplicateButNotProcess += 1;
                                }
                            }
                            else
                            {
                                //reset count loop but it process again
                                countLoopDuplicateButNotProcess = 0;
                                  //remove beforeid in listBeforeId
                                listBeforeId.Remove(item.BeforeId);
                            }
                        }
                        else
                        {
                            //not process
                            countLoopDuplicateButNotProcess += 1;
                        }
                    }
                    //break if not process two times.
                    if (countLoopDuplicateButNotProcess == 2)
                    {
                        break;
                    }
                }
...