Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list in C# with LINQ

Tags:

c#

linq

People also ask

What is sort in C?

Sorting is the process of arranging elements either in ascending (or) descending order. The term sorting came into existence when humans realized the importance of searching quickly.

What is sort () and give example?

Sorting is the process of placing elements from a collection in some kind of order. For example, a list of words could be sorted alphabetically or by length. A list of cities could be sorted by population, by area, or by zip code.

What is sort array in C?

Each element is identified by using an "array index". Accessing array elements is easy by using the array index. The logic we use to sort the array elements in ascending order is as follows − for (i = 0; i < n; ++i){ for (j = i + 1; j < n; ++j){ if (num[i] > num[j]){ a = num[i]; num[i] = num[j]; num[j] = a; } } }


Well, the simplest way using LINQ would be something like this:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true, but the first form makes it clearer IMO, because everyone knows that 0 < 1.

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. If you want to sort in place, you should use the List<T>.Sort method.


Like this?

In LINQ:

var sortedList = originalList.OrderBy(foo => !foo.AVC)
                             .ToList();

Or in-place:

originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));

As Jon Skeet says, the trick here is knowing that false is considered to be 'smaller' than true.

If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo to implement the IComparable<Foo> and IComparable interfaces.


I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();