简体   繁体   中英

How to sort the list by descending order

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.

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)))

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();

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