1

When the Button Click I need to check list is not orderby ascending and dscending when page load. but I need to check if the list is already ordered by ascending I need to ordered by descending , if the list is already ordered by descending need to ordered by ascending. how can I achieve this, I have attahced my code below. can anyone please help me on this??..

 public ActionResult OrderbyName(ResultWrapper wrapper)
 {
      wrapper.HotelDetails = wrapper.HotelDetails.OrderBy(m =>m.Name).ToList();
      //wrapper.HotelDetails = wrapper.HotelDetails.OrderByDescending(m => m.Name).ToList();
      //}
      //else
      //{
      //    wrapper.HotelDetails = wrapper.HotelDetails.OrderByDescending(m => m.Name).ToList();
      //}
      return Json(wrapper);
 }
2
  • 1
    Please break the question into several short and clear sentences. It didn't pass my parser so I don't know what you are asking. Commented Sep 9, 2014 at 10:15
  • Which type is HotelWrapper.HotelDetails - IEnumerable? Commented Sep 9, 2014 at 10:22

3 Answers 3

1

You could just do

wrapper.HotelDetails.Reverse()

return Json(wrapper.HotelDetails) 

which will reverse the current order of the items.

Sign up to request clarification or add additional context in comments.

Comments

0
if (wrapper.HotelDetails.SequenceEqual(wrapper.HotelDetails.OrderBy(m => m.Name)))
{
    wrapper.HotelDetails = wrapper.HotelDetails.OrderByDescending(m => m.Name);
}
else if (wrapper.HotelDetails.SequenceEqual(wrapper.HotelDetails.OrderByDescending(m => m.Name)))
{
    wrapper.HotelDetails = wrapper.HotelDetails.OrderBy(m => m.Name);
}
else
{
    // List isn't ordered, you haven't specified what must be done in this case
}

First of all check if the sequence matches the ascending ordered version of itself, if so order it descending. If it matches the descending ordered version of itself order it ascending. If it's not ordered, you can do either, but you haven't specified this yet (unless I've misunderstood the question).

NOTE: This can be refactored to be more 'elegant' but I've left it as a simple, readable if statement so you can get the jist of what it's doing.

2 Comments

Please note that SequenceEqual enumerates the entire sequence; depending on the length of the sequence this could be quite slow.
@ShellShock - it's true. Whether this is an issue or not depends on OPs data set. If it is an issue, this article discusses a feasible alternative: dotnetperls.com/sequenceequal
0

The answer to this question depends highly on additional information. If you are doing this inside a DataGrid, the answer may be "set AllowSorting to true".

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.