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 th开发者_高级运维is 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?
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;
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);
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.
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;
Although I have not tried it out, this is the correct way according to this great page of samples:
LINQ samples
orderby sample
精彩评论