A day with .Net

My day to day experince in .net

Sort a list by price ascending order – put null or zero values at the end

Posted by vivekcek on October 8, 2012

In this code we sort list by price in ascending order. But we place the zero price to the end using ThenBy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            List<Price> prices = new List<Price>()
                new Price(){ name="a", price=5.0},
                new Price(){ name="b", price=4.0},
                new Price(){ name="c", price=2.0},
                new Price(){ name="d", price=0.0},
                new Price(){ name="e", price=0.0}

            List<Price> sorted = prices.OrderBy(x => x.price == 0).ThenBy(x => x.price).ToList();

    class Price
        public string name;
        public double price;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s