Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I LINQ order a collection

Tags:

c#

linq

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.

like image 771
Samantha J T Star Avatar asked Nov 29 '11 10:11

Samantha J T Star


People also ask

How does OrderBy work in C#?

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.

How do I get data in descending order in LINQ?

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.

What order are LINQ keywords in to perform a query?

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.

What is OrderBy in LINQ C#?

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.


2 Answers

Use OrderBy or OrderByDescending (if you want to sort in descending direction)

var TestsOrdered = tests.OrderBy(x => x.column1);
like image 143
Stecya Avatar answered Oct 05 '22 18:10

Stecya


LINQ:

var result =
from test in tests
orderby test.column1
select test;

Fluent :

var result = tests.OrderBy(x => x.column1);
like image 42
Alex Shkor Avatar answered Oct 05 '22 20:10

Alex Shkor