Paradigm
Paradigm

Reputation: 161

If Statement within Linq Query

I am attempting to sort dropdownlist just exactly how it is entered in the database only if a specific id is selected. Otherwise I want them to sorted in ascending order. I was not sure how to add the final component of not sorting the list when a particular Id is selected. Here is where i am so far:

var items = (from p in _db.Funds
                     where p.DesignationId == id
                     orderby p.Name ascending 
                     select new { p.id, p.Name });
        return items;

Upvotes: 2

Views: 17698

Answers (2)

Abbas Amiri
Abbas Amiri

Reputation: 3204

It would be a solution

var items = (from p in _db.Funds
                 where p.DesignationId == id
                 orderby p.id == "the id" ? p.Name : null 
                 select new { p.id, p.Name });
return items;

Upvotes: 2

p.s.w.g
p.s.w.g

Reputation: 149020

You mean something like this?

var items = 
    (from p in _db.Funds
     where p.DesignationId == id
     select new { p.id, p.Name });
if (id != "some id")
{
    items = items.OrderBy(p => p.Name);
}

return items.ToList();

Upvotes: 8

Related Questions