0

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?

1 Answer 1

1

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 expres­sions are trans­lated into their lambda expres­sions before they’re com­piled.

Sign up to request clarification or add additional context in comments.

3 Comments

You also need to add : using System.Linq; at the top of your file.
can I keep the sorted result as an array?
@user107761 Of course just change ToList() to ToArray().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.