0

I'd like to sort this list according to the ref and name

What should I type instead of && ?

list.Sort((x, y) => x.ref.CompareTo(y.ref) && x.name.CompareTo(y.name));
1
  • 1
    Maybe +? It depends on what your intent is when comparing the objects. What specifically makes one instance of x "greater than" or "less than" another? Commented May 11, 2019 at 18:06

3 Answers 3

2

Use LINQ:

var sorted = list.OrderBy(x => x.ref).ThenBy(x => x.name);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that while being simple, this creates a new enumeration instead of sorting the existing list in-place, as the OP does.
1

CompareTo yields -1, 0 or 1. A negative number means "first value is less than the second", 0 means "both are equal" and a positive value means "first value is greater than the second". So you could simply sort with

list.Sort((x, y) => 2 * x.ref.CompareTo(y.ref) + x.name.CompareTo(y.name));

by giving precedence to the sort order of ref by multiplying it by 2. Only if the refs are equal, the name has a chance to determine the sign.

If you prefer to first sort by name

list.Sort((x, y) => x.ref.CompareTo(y.ref) + 2 * x.name.CompareTo(y.name));

Comments

0

If you want to sort first by ref, then by name, using that syntax, it would look like this:

list.Sort((x,y)=> {
   var comp = x.ref.CompareTo(y.ref);
   if (comp == 0)
      return x.name.CompareTo(y.name);
   else
      return comp;
});

The idea is that you only compare name if ref is equal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.