I have a collection of class objects:
Tests
This collection contains many Test
instances:
public class Test {
public string column1 { get; set; }
}
I would like to use LINQ to order the contents of Tests
and put into a new collection called TestsOrdered
. I want to order by the contents of column1
. I would like to do this with LINQ as later I want to add more to the ordering.
How can I do this with LINQ.
In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.
If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.
The LINQ query syntax starts with from keyword and ends with select keyword. The following is a sample LINQ query that returns a collection of strings which contains a word "Tutorials". The following figure shows the structure of LINQ query syntax. Query syntax starts with a From clause followed by a Range variable.
LINQ-OrderBy sorts the values in the collection on the basis of the specified field in ascending or descending manner. By default, it sorts the collection of elements in ascending order. This is because the main purpose of the order_by operator is to re-arranging the elements in the series in ascending.
Use OrderBy or OrderByDescending (if you want to sort in descending direction)
var TestsOrdered = tests.OrderBy(x => x.column1);
LINQ:
var result =
from test in tests
orderby test.column1
select test;
Fluent :
var result = tests.OrderBy(x => x.column1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With