Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 77 - Sort a list of simple types in c#

Suggested Videos 
Part 74 - List collection class in c#
Part 75 - List collection class in c# continued
Part 76 - Working with generic list class and ranges in c#



Sorting a list of simple types like int, string, char etc, is straight forward. Just invoke Sort() method on the list instance and the data will be automatically sorted in ascending order.
List<int> numbers = new List<int> { 1, 8, 7, 5, 2, 3, 4, 9, 6 };
numbers.Sort();



If you want the data to be retrieved in descending order, use Reverse() method on the list instance.
numbers.Reverse();

However, when you do the same thing on a complex type like Customer, we get a runtime invalid operation exception - Failed to compare 2 elements in the array. This because, .NET runtime does not know, how to sort complex types. We have to tell the way we want data to be sorted in the list by implementing IComparable interface. We will discuss this in a later video session.

So, the next obvious question - How is the sort functionality working for simple types like int, string, char etc?
That is because these types (int, string, decimal, char etc) have implemented IComparable interface already.

Here is the example code used in demo:
public class Program
{
    public static void Main()
    {
        List<int> numbers = new List<int> { 1, 8, 7, 5, 2, 3, 4, 9, 6 };

        Console.WriteLine("Numbers before sorting");
        foreach (int i in numbers)
        {
            Console.WriteLine(i);
        }

        // Sort() will sort data in ascending order 
        numbers.Sort();

        Console.WriteLine("Numbers after sorting");
        foreach (int i in numbers)
        {
            Console.WriteLine(i);
        }

        // Use Reverse() method to retrieve data in descending order
        numbers.Reverse();

        Console.WriteLine("Numbers in descending order");
        foreach (int i in numbers)
        {
            Console.WriteLine(i);
        }

        List<string> alphabets = new List<string>() { "B", "F", "D", "E", "A", "C" };

        Console.WriteLine("Alphabets before sorting");
        foreach (string alphabet in alphabets)
        {
            Console.WriteLine(alphabet);
        }

        alphabets.Sort();

        Console.WriteLine("Alphabets after sorting");
        foreach (string alphabet in alphabets)
        {
            Console.WriteLine(alphabet);
        }

        alphabets.Reverse();

        Console.WriteLine("Alpabets in descending order");
        foreach (string alphabet in alphabets)
        {
            Console.WriteLine(alphabet);
        }

        Customer customer1 = new Customer()
        {
            ID = 101,
            Name = "Mark",
            Salary = 4000
        };

        Customer customer2 = new Customer()
        {
            ID = 102,
            Name = "Pam",
            Salary = 7000
        };

        Customer customer3 = new Customer()
        {
            ID = 103,
            Name = "Rob",
            Salary = 5500
        };

        List<Customer> listCustomers = new List<Customer>();
        listCustomers.Add(customer1);
        listCustomers.Add(customer2);
        listCustomers.Add(customer3);

        Console.WriteLine("Customers before sorting");
        foreach (Customer customer in listCustomers)
        {
            Console.WriteLine(customer.Name);
        }

        // Invoking Sort() on list of complex types will 
        // throw invalid operation exception, unless 
        // IComparable interface is implemented
        listCustomers.Sort();
            
        Console.WriteLine("Customers after sorting");
        foreach (Customer customer in listCustomers)
        {
            Console.WriteLine(customer.Name);
        }
    }
}

public class Customer 
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }

}

Part 76 - Working with generic list class and ranges in c#

Suggested Videos 
Part 73 - What is dictionary in c# continued
Part 74 - List collection class in c#
Part 75 - List collection class in c# continued



Please watch Part 74 & 75 before proceeding with this video. In thie video, we will discuss

1. AddRange() - Add() method allows you to add one item at a time to the end of the list, where as AddRange() allows you to add another list of items, to the end of the list.

2. GetRange() - Using an item index, we can retrieve only one item at a time from the list, if you want to get a list of items from the list, then use GetRange() function. This function expects 2 parameters, i.e the start index in the list and the number of elements to return.

3. InsertRange() - Insert() method allows you to insert a single item into the list at a specificed index, where as InsertRange() allows you, to insert another list of items to your list at the specified index.

4. RemoveRange() - Remove() function removes only the first matching item from the list. RemoveAt() function, removes the item at the specified index in the list. RemoveAll() function removes all the items that matches the specified condition. RemoveRange() method removes a range of elements from the list. This function expects 2 parameters, i.e the start index in the list and the number of elements to remove. If you want to remove all the elements from the list without specifying any condition, then use Clear() function.



public class Program
{
    public static void Main()
    {
        // Create Customer Objects
        Customer customer1 = new Customer()
        {
            ID = 101,
            Name = "Mark",
            Salary = 4000,
            Type = "RetailCustomer"
        };

        Customer customer2 = new Customer()
        {
            ID = 102,
            Name = "Pam",
            Salary = 7000,
            Type = "RetailCustomer"
        };

        Customer customer3 = new Customer()
        {
            ID = 103,
            Name = "Rob",
            Salary = 5500,
            Type = "RetailCustomer"
        };

        Customer customer4 = new Customer()
        {
            ID = 104,
            Name = "John",
            Salary = 6500,
            Type = "CorporateCustomer"
        };

        Customer customer5 = new Customer()
        {
            ID = 105,
            Name = "Sam",
            Salary = 3500,
            Type = "CorporateCustomer"
        };

        
        List<Customer> listCustomers = new List<Customer>();
        // Add() method allows you to add one at a time to the end of the list
        listCustomers.Add(customer1);
        listCustomers.Add(customer2);
        listCustomers.Add(customer3);

        List<Customer> listCorporateCustomers = new List<Customer>();
        listCorporateCustomers.Add(customer4);
        listCorporateCustomers.Add(customer5);

        // AddRange() allows you to add another list of items, to the end of the list
        listCustomers.AddRange(listCorporateCustomers);

        foreach (Customer customer in listCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}, Type = {3}",
                customer.ID, customer.Name, customer.Salary, customer.Type);
        }
        Console.WriteLine("------------------------------------------------------");

        // GetRange() function returns a list of items from the list.
        List<Customer> corporateCustomers = listCustomers.GetRange(3, 2);
        foreach (Customer customer in corporateCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}, Type = {3}",
                customer.ID, customer.Name, customer.Salary, customer.Type);
        }
        Console.WriteLine("------------------------------------------------------");

        // Remove() function removes only the first matching item from the list.
        listCustomers.Remove(customer1);

        // RemoveAt() function, removes the item at the specified index in the list.
        listCustomers.RemoveAt(0);

        // RemoveAll() function removes all the items that matches the specified condition.
        listCustomers.RemoveAll(x => x.Type == "RetailCustomer");

        foreach (Customer customer in listCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}, Type = {3}",
                customer.ID, customer.Name, customer.Salary, customer.Type);
        }
        Console.WriteLine("------------------------------------------------------");

        // RemoveRange() method removes a range of elements from the list. 
        // This function expects 2 parameters, i.e the start index in the 
        // list and the number of elements to remove.
        listCustomers.RemoveRange(0, 2);

        // Insert() method allows you to insert a single item at a time into 
        // the list at a specificed index
        listCustomers.Insert(0, customer1);
        listCustomers.Insert(1, customer2);
        listCustomers.Insert(2, customer3);

        // InsertRange() allows you, to insert another list of items to your list at the specified index
        listCustomers.InsertRange(0, listCorporateCustomers);

        foreach (Customer customer in listCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}, Type = {3}",
                customer.ID, customer.Name, customer.Salary, customer.Type);
        }
        Console.WriteLine("------------------------------------------------------");

        // If you want to remove all the elements from the list without specifying 
        // any condition, then use Clear() function.
        listCustomers.Clear();

        Console.WriteLine(" Total Items in the List = " + listCustomers.Count);
    }
}

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
    public string Type { get; set; }
}

Part 75 - List collection class in c# continued

Suggested Videos 
Part 72 - What is dictionary in c#
Part 73 - What is dictionary in c# continued
Part 74 - List collection class in c#



This is continuation to Part 74. So, please watch Part 74, before proceeding. In this video, we will discuss
1. Contains() function - Use this function to check if an item exists in the list. This method returns true if the items exists, else false.

2. Exists() function - Use this function, to check if an item exists in the list based on a condition. This method returns true if the items exists, else false.

3. Find() function - This method searches for an element that matches the conditions defined by the specified lambda expression and returns the first matching item from the list.

4. FindLast() function - This method searches for an element that matches the conditions defined by the specified lambda expression and returns the Last matching item from the list.

5. FindAll() function - This method returns all the items from the list that match the conditions specified by the lambda expression.



6. FindIndex() function - This method returns the index of the first item, that matches the condition specified by the lambda expression. There are 2 other overloads of this method which allows us to specify the range of elements to search, with in the list.

7. FindLastIndex() function - This method returns the index of the last item, that matches the condition specified by the lambda expression. There are 2 other overloads of this method which allows us to specify the range of elements to search, with in the list.

8. Convert an array to a List - Use ToList() method

9. Convert a list to an array - Use ToArray() method

10. Convert a List to a Dictionary - Use ToDictionary() method

public class Program
{
    public static void Main()
    {
        // Create Customer Objects
        Customer customer1 = new Customer()
        {
            ID = 101,
            Name = "Mark",
            Salary = 4000
        };

        Customer customer2 = new Customer()
        {
            ID = 102,
            Name = "Pam",
            Salary = 7000
        };

        Customer customer3 = new Customer()
        {
            ID = 104,
            Name = "Rob",
            Salary = 5500
        };

        Customer[] arrayCustomers = new Customer[3];
        arrayCustomers[0] = customer1;
        arrayCustomers[1] = customer2;
        arrayCustomers[2] = customer3;

        // To convert an array to a List, use ToList() method
        List<Customer> listCustomers = arrayCustomers.ToList();
        foreach (Customer c in listCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", c.ID, c.Name, c.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // To convert a List to an array, use ToLArray() method
        Customer[] arrayAllCustomers = listCustomers.ToArray();
        foreach (Customer c in arrayAllCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", c.ID, c.Name, c.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // To convert a List to a Dictionary use ToDictionary() method
        Dictionary<intCustomer> dictionaryCustomers = listCustomers.ToDictionary(x => x.ID);
        foreach (KeyValuePair<intCustomer> keyValuePairCustomers in dictionaryCustomers)
        {
            Console.WriteLine("Key = {0}", keyValuePairCustomers.Key);
            Customer c = keyValuePairCustomers.Value;
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", c.ID, c.Name, c.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // To check if an item exists in the list use Contains() function
        // This method returns true if the items exists, else false
        if (listCustomers.Contains(customer2))
        {
            Console.WriteLine("Customer2 object exists in the list");
        }
        else
        {
            Console.WriteLine("Customer2 object does not exist in the list");
        }
        Console.WriteLine("------------------------------------------------------");

        // To check if an item exists in the list based on a condition, then use Exists() function
        // This method returns true if the items exists, else false
        if (listCustomers.Exists(x => x.Name.StartsWith("M")))
        {
            Console.WriteLine("List contains customer whose name starts with M");
        }
        else
        {
            Console.WriteLine("List does not contain a customer whose name starts with M");
        }
        Console.WriteLine("------------------------------------------------------");

        // Find() method searches for an element that matches the conditions defined by 
        // the specified lambda expression and returns the first matching item from the list
        Customer cust = listCustomers.Find(customer => customer.Salary > 5000);
        Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cust.ID, cust.Name, cust.Salary);
        Console.WriteLine("------------------------------------------------------");

        // FindLast() method searches for an element that matches the conditions defined
        // by the specified lambda expression and returns the Last matching item from the list
        Customer lastMatch = listCustomers.FindLast(customer => customer.Salary > 5000);
        Console WriteLine("ID = {0}, Name = {1}, Salary = {2}", lastMatch.ID, lastMatch.Name, lastMatch.Salary);
        Console.WriteLine("------------------------------------------------------");

        // FindAll() method returns all the items from the list that
        // match the conditions specified by the lambda expression
        List<Customer> filteredCustomers = listCustomers.FindAll(customer => customer.Salary > 5000);
        foreach (Customer cstmr in filteredCustomers)
        {
            Console.WriteLine("ID = {0}, Name = {1}, Salary = {2}", cstmr.ID, cstmr.Name, cstmr.Salary);
        }
        Console.WriteLine("------------------------------------------------------");

        // FindIndex() method returns the index of the first item, that matches the 
        // condition specified by the lambda expression. There are 2 other overloads
        // of this method which allows us to specify the range of elements to 

        // search, with in the list.
        Console.WriteLine("Index of the first matching customer object whose salary is greater 5000 =" +
            listCustomers.FindIndex(customer => customer.Salary > 5000));
        Console.WriteLine("------------------------------------------------------");

        // FindLastIndex() method returns the index of the last item, 
        // that matches the condition specified by the lambda expression. 
        // There are 2 other overloads of this method which allows us to specify 
        // the range of elements to search, with in the list.
        Console.WriteLine("Index of the Last matching customer object whose salary is greater 5000 = " +
            listCustomers.FindLastIndex(customer => customer.Salary > 5000));
        Console.WriteLine("------------------------------------------------------");
    }
}

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
}

Part 35 – Indexes





Part 34 – Temporary Tables







Part 33 – Functions – Important Concepts




Part 32 – Multi-Statement Table Valued Functions




Part 31 – Inline Table Valued Functions




Part 30 – User defined functions