-1

I have the following code:

      public ActionResult ViewCategory(string categoryName, string searchCriteria = "Price")
    {
        // Retrieve Category and its associated Listings from the database
        var categoryModel = db.Categories.Include("Listings")
            .Single(c => c.Title == categoryName);

        var viewModel = new ClassifiedsBrowseViewModel
        {
            Category = categoryModel,
            Listings = categoryModel.Listings.ToList()
        };

        return View(viewModel);
    }

This code returns some listings from a given category.

But I want to re-order these search results based on certain criteria. E.G. Price...

Many Thanks, J

JHarley1
  • 2,026
  • 6
  • 24
  • 34
  • Why would you need to do a GroupBy when you're selecting a single row anyway? – Justin Niessner Nov 11 '10 at 16:54
  • What are you trying to group by? Why are you including Listings? Is that part of your group by or not related? – Steve Michelotti Nov 11 '10 at 16:56
  • Sorry I have updated my question to add the full code, basically I have a classified site. I have different categories and within those categories I have listings, this page simply retrieves the listings for that specific category... but how do I change the order of those listings? – JHarley1 Nov 11 '10 at 17:00

4 Answers4

1
Listings = categoryModel.Listings.OrderBy(x => x.Price).ToList();
UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
1

You want to use OrderBy() or OrderByDescending() depending upon on requirements.

For example ordering it by highest price -

var viewModel = new ClassifiedsBrowseViewModel
        {
            Category = categoryModel,
            Listings = categoryModel.Listings.OrderByDescending(c=>c.Price).ToList()
        };
Vishal
  • 12,133
  • 17
  • 82
  • 128
  • Hello, Thanks for the advice upthecreek and misnomer. How would I search by the contents of the search criteria string? – JHarley1 Nov 11 '10 at 17:12
  • I am afraid dont completely understand...but if you mean order by dynamically by string value -http://stackoverflow.com/questions/41244/dynamic-linq-orderby – Vishal Nov 11 '10 at 17:15
  • Use a switch statement, test for each string you are expecting, perform a different query in each case... http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx – UpTheCreek Nov 11 '10 at 19:26
0

Another option that might work, depending on how you present the information: use something like the jquery tablesorter plugin, and sort the results on the client side.

Obviously, this won't work if there are a lot of results, and you're doing paging, but for a single page of results, presented in a table, it works great.

chris
  • 36,094
  • 53
  • 157
  • 237
0

Another way to write the Linq is to use the query language:

Listings = from item in categoryModel.Listings
           orderby item.Price
           select item;
Berin Loritsch
  • 11,400
  • 4
  • 30
  • 57