C Sharp Code Snippets

12/5/2014 5:13:33 AM
A library of simple C # code snippets for reference.

Easily forgettable but useful C# code snippets.

Lists - Sort a list of objects

Lists

Sorting a list of objects

Here's a simple class to use for this example.

    public class SimpleClass
    {
        public int ID;
        public string SomeValue;
        public SimpleClass(int id, string someValue)
        {
            ID = id;
            SomeValue = someValue;
        }
    }
    

Create a list of SimpleClass objects and add populated objects to it

        private void button1_Click(object sender, EventArgs e)
        {
            List lstSimpleClasses = new List();
            lstSimpleClasses.Add(new SimpleClass(1, "Alpha"));
            lstSimpleClasses.Add(new SimpleClass(2, "Bravo"));
            lstSimpleClasses.Add(new SimpleClass(3, "Charlie"));
            lstSimpleClasses.Add(new SimpleClass(4, "Delta"));
            lstSimpleClasses.Add(new SimpleClass(5, "Echo"));
            textBox1.Text = string.Empty;
            foreach(SimpleClass oSC in lstSimpleClasses)
            {
                textBox1.Text += oSC.ID.ToString() +" "+ oSC.SomeValue + Environment.NewLine;
            }
            textBox1.Text += "----------- SORTED -----------" + Environment.NewLine;
            var alphabetizedDescending = from x in lstSimpleClasses
                                         orderby x.SomeValue descending
                                         select x;
            foreach (SimpleClass oSC in alphabetizedDescending)
            {
                textBox1.Text += oSC.ID.ToString() + " " + oSC.SomeValue + Environment.NewLine;
            }
        }
    

Output: