Reputation: 1757
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;}
}
Upvotes: 1
Views: 14285
Reputation: 1757
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();
}
Upvotes: 0
Reputation: 2702
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();
Upvotes: 2
Reputation: 460028
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
?
Upvotes: 4