# Ordering first by non 0 values - how?

• ### Question

• Hello everyone,

I have a LINQ query that brings me a list of products with the minimum price the suppliers have for it, but some products have the price 0 when they are unavailable. Is there any way of ordering first for the non-0 values, and then by then (since I don't want the products to be hidden or not listed)?

Marcelo

Marcelo
http://www.eopreco.com.br - Price Comparison. Need the lowest price? We find it for you.
Thursday, June 30, 2011 4:38 AM

• Hi,

Yes, it is almost the same, just in two steps.

Based on that solution it should look like this:

```var ordered = Products.OrderBy(p => (p.Price == 0) ? 1 : 0).ThenBy(p => p.Price);
```

Regards, Peter

• Proposed as answer by Thursday, July 7, 2011 12:23 PM
• Marked as answer by Monday, July 11, 2011 9:57 AM
Thursday, June 30, 2011 12:16 PM
• Hi mnmagri;

You can use the OrderByDescending /orderby method to place all the zero values at the end of the list of objects. The following is an examples of its use.

var prods = DataContextInstance.Products.OrderByDescending( p => p.price );

or

```var prods = from p in DataContextInstance.Products
orderby p.price descending
select p;
```

Fernando

Thursday, June 30, 2011 6:07 PM

### All replies

When you are using the .OrderBy method you can define a key selector. A function to extract a key from an element.

To achieve your goal you can do the following:

`var ordered = Products.OrderBy(p => (p.Price == 0) ? int.MaxValue : p.Price);`

So all of the products will be shorted by their own Price except those with 0.

Regards, Peter

Thursday, June 30, 2011 8:24 AM
• Hi,

Here you have a similar thread, but just the opposite you need to do:

http://stackoverflow.com/questions/5340037/linq-orderbydescending-but-keep-zero-value-first

Regards,

JA Reyes.

Por favor, recuerda Votar y "Marcar como respuesta" si la solución de esta pregunta te ha sido útil.
Thursday, June 30, 2011 12:07 PM
• Hi,

Yes, it is almost the same, just in two steps.

Based on that solution it should look like this:

```var ordered = Products.OrderBy(p => (p.Price == 0) ? 1 : 0).ThenBy(p => p.Price);
```

Regards, Peter

• Proposed as answer by Thursday, July 7, 2011 12:23 PM
• Marked as answer by Monday, July 11, 2011 9:57 AM
Thursday, June 30, 2011 12:16 PM
• Hi mnmagri;

You can use the OrderByDescending /orderby method to place all the zero values at the end of the list of objects. The following is an examples of its use.

var prods = DataContextInstance.Products.OrderByDescending( p => p.price );

or

```var prods = from p in DataContextInstance.Products
orderby p.price descending
select p;
```

Fernando