简体   繁体   中英

sort an array of structs with multiple criteria c#

I have an array of structs which needs to be sorted first by st, then by priority and then by id. this is my struct:

 struct File {  
   public int priority, id, st;
 }

and this is my array:

 File[] Files = new File[10];

is there an easy way to do that kind of sorting?

You can use OrderBy and ThenBy methods from the System.Linq namespace:

var result = Files.OrderBy(x => x.st)
                  .ThenBy(x => x.priority)
                  .ThenBy(x => x.id)
                  .ToList(); // Or ToArray()

You can also use Query Syntax for such Linq query:

var result = (from file in Files
             orderby file.st, file.priority, file.id
             select file).ToList(); // Or ToArray()

Keep in mind that query expressions are translated into their lambda expressions before they're compiled.

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