C# List Sort(Int32, Int32, IComparer)

Description

List Sort(Int32, Int32, IComparer ) sorts the elements in a range of elements in List using the specified comparer.

Syntax


public void Sort(
  int index,//from   ww  w . j  a  v a 2  s.c o m
  int count,
  IComparer<T> comparer
)

Parameters

  • index - The zero-based starting index of the range to sort.
  • count - The length of the range to sort.
  • comparer - The IComparer implementation to use when comparing elements, or null to use the default comparer Comparer .Default.

Example


using System;//from w w w. j  a  v  a2 s .  c  om
using System.Collections.Generic;

using System.Collections;
using System.ComponentModel;

public class Product
{
    string name;
    public string Name
    {
        get { return name; }
    }

    decimal price;
    public decimal Price
    {
        get { return price; }
    }

    public Product(string name, decimal price)
    {
        this.name = name;
        this.price = price;
    }

    public static List<Product> GetSampleProducts()
    {
        List<Product> list = new List<Product>();
        list.Add(new Product("C", 9.99m));
        list.Add(new Product("A", 1.99m));
        list.Add(new Product("F", 2.99m));
        list.Add(new Product("S", 3.99m));
        return list;
    }

    public override string ToString()
    {
        return string.Format("{0}: {1}", name, price);
    }
}
class ListSortWithComparer
{
    class ProductNameComparer : IComparer<Product>
    {
        public int Compare(Product first, Product second)
        {
            return first.Name.CompareTo(second.Name);
        }
    }

    static void Main()
    {
        List<Product> products = Product.GetSampleProducts();
        products.Sort(1,2,new ProductNameComparer());
        foreach (Product product in products)
        {
            Console.WriteLine(product);
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections.Generic »




HashSet
LinkedList
LinkedListNode
List
Queue
SortedSet
Stack