Nithin Paul
Nithin Paul

Reputation: 2199

Use Linq to query in order except the one record

I have one table in my DB containing set of names. I need to use order by condition to sort the names alphabetically except one name which should print on top of the list if the user name is Say 'John'. I got one SQL query, but How do i use this following query in linq?

SELECT name
FROM names
ORDER BY
  CASE WHEN name = 'John' THEN 0 ELSE 1 END,
name

Upvotes: 2

Views: 1197

Answers (3)

Enigmativity
Enigmativity

Reputation: 117084

You could also do it this way:

var result =
    db.names
        .ToArray()
        .OrderBy(x => (x.Name == "John" ? "0" : "1") + x.Name)
        .ToArray()

Upvotes: 3

Rahul Singh
Rahul Singh

Reputation: 21805

Try this:-

var result = db.names.Where(x => x.Name == "John")
                     .Concat(db.names.Where(x => x.Name != "John")
                     .OrderBy(x => x.Name)).ToList();

Upvotes: 1

Monah
Monah

Reputation: 6794

you can do the following

var listWithoutJohn=db.names.Where(t=>t.name!="John").OrderBy(t=>t.name).ToArray();
var johnList=db.names.Where(t=>t.name=="John").ToList();
var result=johnList.AddRange(listWithoutJohn);

hope this will help you

Upvotes: 1

Related Questions