Daniel B
Daniel B

Reputation: 8879

Select one column, order by another

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?

Upvotes: 14

Views: 28559

Answers (4)

hadi.sh
hadi.sh

Reputation: 129

Try this:

int id =Convert.ToInt32(db.Table.Single(x => x.Id == id_factor).Id);

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564771

You would rewrite this as:

var query = from vk in db.Valdkurs 
            where vk.pnr == pnr 
            orderby vk.prioritet descending
            select vk.kursnamn;

Upvotes: 6

David
David

Reputation: 219037

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.)

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

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.

Upvotes: 18

Related Questions