Home > Blockchain >  How to sort the list by descending order
How to sort the list by descending order

Time:11-30

public class Items {
   public string Name {get; set;}
   public int Id {get; set;}
   public List<string> SubItems {get; set;}
}

Above is my class. And somewhere in my code I am using List and adding the records.

List<Items> listOfItems = new List<Items>();
listOfItems.OrderByDescending(i => i.SubItems).ToList();

listOfItems has some data. I want to order the SubItems which are in listOfItems list through LINQ query.

CodePudding user response:

You can't do it with LINQ, as LINQ is query, and you want to change your data in place, not to query something from the data. But you still can use ordinal loop for sorting the content for each Item

listOfItems.ForEach(x=>x.SubItems.Sort((a, b) => b.CompareTo(a)))

or

listOfItems.ForEach(x=>x.SubItems = x.SubItems.OrderByDescending(i => i)))

CodePudding user response:

I think the issue here is that the OrderBy() returns new list, which you are currently not storing anywhere. So it should be:

List<Items> listOfItems = new List<Items>();

var orderedList = listOfItems.OrderByDescending(i => i.SubItems).ToList();
  • Related