James
James

Reputation: 13

LINQ to SQL Expression "Orderby" help

I current have a LINQ expression, although I would like to know it its possible to use the "orderby" directive in conjunction with a specific field in this case "CDGenre" e.g.

DataClassesDataContext db = new DataClassesDataContext (); {
from p in db.ArtistName
**orderby p.CDGenre** accending;
select p.CDTitle;
}

Will this statement achieve this?

Upvotes: 1

Views: 517

Answers (5)

Brett
Brett

Reputation: 4061

The syntax looks right to me, there's also the option of:

(from p in db.ArtistName
select p.CDTitle).OrderBy(p => p.CDGenre);

edit: you could select into an object if you want multiple things in the select statement:

(from p in db.ArtistName
select new CDObject(p.CDTitle,p.CDGenre,p.CDArtist)).OrderBy(p => p.CDGenre);

Upvotes: 1

Mozy
Mozy

Reputation: 31

Although I have not tried it out, this is the correct way according to this great page of samples:

LINQ samples

orderby sample

Upvotes: 0

SirViver
SirViver

Reputation: 2441

Your main idea was already correct, though the default sort order is already ascending, so no extras are required.

from p in db.ArtistName
orderby p.CDGenre
select p.CDTitle;

For descending order, use

from p in db.ArtistName
orderby p.CDGenre descending
select p.CDTitle;

Upvotes: 0

mdm
mdm

Reputation: 12630

From 101 Linq Samples:

public void Linq29()
{
    string[] words = { "cherry", "apple", "blueberry" };

    var sortedWords =
        from w in words
        orderby w.Length
        select w;

    Console.WriteLine("The sorted list of words (by length):");
    foreach (var w in sortedWords)
    {
        Console.WriteLine(w);
    }
}

Your code snippet looks almost right, but won't compile:

from p in db.ArtistName
orderby p.CDGenre ascending
select p.CDTitle;

Should work.

Upvotes: 0

bruno conde
bruno conde

Reputation: 48265

It's "ascending" not "accending". Maybe that was the problem (and the semicolon in the end):

from p in db.ArtistName
orderby p.CDGenre ascending
select p.CDTitle;

Upvotes: 3

Related Questions