I'm using LINQ to SQL to select from a database. I want to select one column that consists of values that are String
, but order by another column that contains a "priority"-value that is an int
.
This is what my LINQ statement looks like right now:
var query = from vk in db.Valdkurs
where vk.pnr == pnr
select vk.kursnamn.OrderByDescending(x => vk.prioritet);
On the third line of code a NotSupportedException
is thrown with the exception message
Sequence operators not supported for type 'System.String'
I have come to the conclusion that it is probably because of the
vk.kursnamn.OrderByDescending(x => vk.prioritet);
where vk.Kursnamn
is of String
type.
How can I select the vk.Kursnamn
and order them by the vk.Priority
?
Discussion: If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query.
The order doesn't matter, actually, so you are free to order them however you'd like. edit: I guess a bit more background is helpful: As far as I know, the process of optimizing any query happens prior to determining exactly what subset of the row data is being pulled.
After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name). You can modify the sorting order (ascending or descending) separately for each column.
You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.
You need to first order, and then select, like this:
var query = db.Valdkurs
.Where(vk=> vk.pnr == pnr) // Filter
.OrderBy(vk => vk.prioritet) // prioritet is still here - order by it
.Select(vk => vk.kursnamn); // Now grab the kursnamn
Otherwise, LINQ thinks that you are trying to order the characters of the string
, which is not a supported operation.
You would rewrite this as:
var query = from vk in db.Valdkurs
where vk.pnr == pnr
orderby vk.prioritet descending
select vk.kursnamn;
I'm not sure of the LINQ syntax, but essentially what you're trying to do is:
var query = db.Valdkurs
.Where(vk=> vk.pnr == pnr)
.OrderByDescending(vk => vk.prioritet)
.Select(vk => vk.kursnamn);
You can chain these together in all sorts of ways. Essentially each one modifies the collection and returns the modified collection. (Or at least they will evaluate that way when they're executed, which happens when you call .ToList()
for example.)
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