简体   繁体   中英

How to Order By list inside list using LINQ in C#

I want to Order by "SortKey" first list and second list inside first list, but I can't do it. Please get me your advice how to order lists using LINQ.

//Get Data and put in myList
List<Group1> myList = GetData(); 

//Sort
//Visual studio do not get compilation error but this code doesn't working at the run-time.
var SortedData = myList.Select(x => x).OrderBy(x=> x.SortKey).ThenBy(y=> y.Group2.OrderBy(x=> x.SortKey)).ToList();

Model:

public class Group1
{
   public int Id {get;set;}
   public string Name {get;set;}
   public int Sortkey {get;set;}
   public List<Group2> {get;set;}
}
public class Group2
{
   public int Id {get;set;}
   public string Name {get;set;}
   public int Sortkey {get;set;}
}

You cannot re-order the innerlist with a LINQ query. The only way is to create a new ordered list. I suggest to use a simple loop and List.Sort :

List<Group1> myList = GetData();
myList.Sort((x1, x2) => x2.SortKey.CompareTo(x2.SortKey));
foreach(Group1 item in myList)
{
    item.Group2.Sort((x1, x2) => x2.SortKey.CompareTo(x2.SortKey));
}

If you want to use LINQ ( List.Sort is more efficient):

List<Group1> myList = GetData().OrderBy(x => x.SortKey).ToList();
foreach(Group1 item in myList)
{
    item.Group2 = item.Group2.OrderBy(x => x.SortKey).ToList();
}

But why can't you order the lists in GetData ?

I am not good with LINQ and i haven't tested this solution but what about this:

HINT: This solution may not be good, because it has side effects (see comment on other answer)

assuming you have these classes:

public class Group1
{
   public int Id {get;set;}
   public string Name {get;set;}
   public int Sortkey {get;set;}
   public List<Group2> Categories {get;set;}
}

public class Group2
{
   public int Id {get;set;}
   public string Name {get;set;}
   public int Sortkey {get;set;}
}

// Order first List with the first OrderBy
var sortedList = myList.OrderBy(
    x =>
        {
            // x equals a element in the list
            // foreach x you want to sort the second list 
            // and assign it back to x.Categories
            x.Categories = x.Categories.OrderBy(y => y.Sortkey).ToList();
            return x.Sortkey;
        }).ToList();

I test this code and everything is working well.

 var result = MyList.OrderBy(x => x.SortKey).ToList();
                foreach (var item in model)
                {
                   item.Group2 = item.Categories.OrderBy(x => x.SortKey).ToList();
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM