2

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;
1
  • 2
    What do you mean by "exactly how it is entered in the database"? You should regard rows in a database table as unordered unless you specify an ordering. Commented Jul 18, 2013 at 18:18

2 Answers 2

8

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();
Sign up to request clarification or add additional context in comments.

9 Comments

Just remember to call ToList() method to execute your query.
p.DesignationId is the Id i wanted it to be based on
This works but wouldn't it perform better if you determined the ordering before hand and made it so orderby is part of the LINQ to SQL query rather than a LINQ to Objects query done after?
@evanmcdonnal The ordering will be executed as a Linq-to-SQL / -Entities query.
@Paradigm So... if no id is selected display everything unordered; if some id is selected just display those items, ordered by Name. Is that right?
|
2

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.