Sort List With Lambda Expression in CSharp

Description

The following code shows how to sort List With Lambda Expression.

Example


//  ww  w  .j  av a 2  s .c  o m
using System.Text;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

class Product
{
    public string Name { get; private set; }
    public decimal Price { get; private set; }

    public static List<Product> GetSampleProducts()
    {
        return new List<Product>
            {
                new Product { Name="C", Price = 9.99m },
                new Product { Name="A", Price=14.99m },
                new Product { Name="F", Price=13.99m },
                new Product { Name="S", Price=10.99m}
            };
    }
    public override string ToString()
    {
        return string.Format("{0}: {1}", Name, Price);
    }
}
class ListSortWithLambdaExpression
{
    static void Main()
    {
        List<Product> products = Product.GetSampleProducts();
        products.Sort((first, second) => first.Name.CompareTo(second.Name));
        foreach (Product product in products)
        {
            Console.WriteLine(product);
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor