Thursday, June 9, 2011

Sorting List Generic collection (string)

This example uses List generic collection and will sort names in descending order. Names with New will be displayed on top of the list. This is applicable if you will be displaying products names with NEW in it's product name as recently displayed.
Code:
  List<string> Names = new List<string>();  
      private void FListSort_Load(object sender, EventArgs e)  
      {  
        Names.Add("Mike");  
        Names.Add("John");  
        Names.Add("Titch");  
        Names.Add("Harold");  
        Names.Add("Klent");  
        Names.Add("Thomas New");  
        Names.Add("Mary");  
        Names.Add("Fultron New");  
        Names.Add("Khayce");  
        Names.Add("Tim");  
        Names.Add("Joker New");  
        Names.Add("Linda");  
        Names.Add("Arthur New");  
        Names.Add("Baby Lee Jones");  
        Names.Add("Caspers New");  
      }  
      internal class MyComp  
      {  
          public int sort(string x, string y)  
          {  
            return x.IndexOf("New").CompareTo(y.IndexOf("New"));  
          }  
      }      
      private void btnSort_Click(object sender, EventArgs e)  
      {  
        MyComp comp = new MyComp();  
        txtSorted.Text = "Sort by Ascending!";  
        //Names.Sort(delegate(string x, string y)   
        //{ return x.IndexOf("New").CompareTo(y.IndexOf("New")); });  
        Names.Sort(comp.sort);  
        txtSorted.Text += Environment.NewLine;  
        txtSorted.Text += Environment.NewLine;  
        txtSorted.Text = "Sort by Descending!" ;  
        txtSorted.Text += Environment.NewLine;  
        txtSorted.Text += Environment.NewLine;  
        Names.Reverse();  
        foreach (string x in Names)  
        {  
          txtSorted.Text = txtSorted.Text + x + Environment.NewLine;  
        }        
      }

Reference: Developer Fusion Article

0 comments:

Post a Comment