Samantha J T Star
Samantha J T Star

Reputation: 32758

How do I LINQ order a collection

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.

Upvotes: 7

Views: 4345

Answers (5)

Stecya
Stecya

Reputation: 23266

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

var TestsOrdered = tests.OrderBy(x => x.column1);

Upvotes: 4

Alex Shkor
Alex Shkor

Reputation: 1209

LINQ:

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

Fluent :

var result = tests.OrderBy(x => x.column1);

Upvotes: 2

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

Can you just do it like this:

var TestsOrdered = Tests.OrderBy( t => t.column1 );

Upvotes: 1

spender
spender

Reputation: 120380

var TestsOrdered = Tests.OrderBy( t => t.column1 );

Upvotes: 1

dknaack
dknaack

Reputation: 60438

List<Test> testList = new List<Test>();
// .. fill your list
testList = testList.OrderBy(x => x.column1).ToList();

Upvotes: 2

Related Questions