Donate

Sorting List<T> Generic Collection String In C#

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.
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

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations