Reputation: 1
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));
Upvotes: 0
Views: 65
Reputation: 112334
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));
Upvotes: 1
Reputation: 6060
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.
Upvotes: 0
Reputation: 13652
Use LINQ:
var sorted = list.OrderBy(x => x.ref).ThenBy(x => x.name);
Upvotes: 2