Practical Usage of Complete Extension Methods in LINQ


In this article we are going to see the complete usage of extension methods in LINQ with the help of a Lambda expression.

Step 1: Used Namespaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

Step 2: Uses of a collection for OfType() method.

public static List<object> ObjCollection()
{
    List<object> list = new List<object>();
    list.Add(1);
    list.Add(9.5f);
    list.Add(2);
    list.Add(2.5f);
    list.Add(2.5M);
    list.Add("Lajapathy");
    list.Add("Arun");
    list.Add('C');
    list.Add(DateTime.Today);
    return list;
}


Step 3: OfType() LINQ method is used to parse the specific data type values form the collection.

public static void LINQOfType()
{
    List<object> list = ObjCollection();

    //This parse the string value alone.
    var listTempStr = list.OfType<string>().ToList();
    PrintLis<string>(listTempStr, "String DataType:");

    //It parses Interger
    var listTempInt = list.OfType<int>().ToList();
    PrintLis<int>(listTempInt, "Interger DataType:");

    //It parses Float.
    var listTempFloat = list.OfType<float>().ToList();
    PrintLis<float>(listTempFloat, "Float DataType:");

    //It parses DateTime.
    var listTempDate = list.OfType<DateTime>().ToList();
    PrintLis<DateTime>(listTempDate, "Date DataType:");
}


Linq1.jpg

Step 4: Simple SequenceEqual() LINQ: compares the items and returns true if the items are equal

 public static void SimpleSequenceEqualLinq()
 {
     IList<int> list1 = new List<int>() { 1, 2, 3 };
     IList<int> list2 = new List<int>() { 1, 2, 3 };
     IList<int> list3 = new List<int>() { 4, 5, 6 };

     bool result1 = list1.SequenceEqual(list2); // True
     bool result2 = list1.SequenceEqual(list3); // False
 }


Step 5: Complex SequenceEqual() LINQ: compares a complex data type for the items and returns true if the items are equal:

        public static void SequenceEqualLinq()
        {
            List<Employee> empList1 = new List<Employee>();
            empList1.Add(new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" });
            empList1.Add(new Employee { ID = 200, Name = "Parthiban", CompanyName = "FE" });
            List<Employee> empList2 = new List<Employee>();
            empList2.Add(new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" });
            empList2.Add(new Employee { ID = 200, Name = "Parthiban", CompanyName = "FE" });

            //It is false because we have added directly to list
            // So it dont know the reference code.
            bool isSequence = empList1.SequenceEqual(empList2);//FALSE
            HttpContext.Current.Response.Write(isSequence + "<br/>");

            Employee emp1 = new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" };
            Employee emp2 = new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" };

            empList1 = new List<Employee>();
            empList1.Add(emp1);
            empList1.Add(emp2);

            empList2 = new List<Employee>();
            empList2.Add(emp1);
            empList2.Add(emp2);

            //It is true because it created separately and know its reference code.
            isSequence = empList1.SequenceEqual(empList2);//TRUE
            HttpContext.Current.Response.Write(isSequence + "<br/>");
        }

Linq2.jpg

Step 6: Simple of filtering items based on the condition:

public static void SimpleWhere()
{
    string userInput = "Lajapathy";
    List<string> list = GetStringList();

    //Here Filter the list based on user input;
    List<string> listStr = list.Where(name => name == userInput).ToList();

    PrintLis<string>(listStr, "Filter by Name:");
}

Linq3.jpg

Step 7: Complex Where() LINQ -> filtering items based on the condition:

public static void ComplexWhere()
{
    string userInput = "Lajapathy";

    //Employee collection
    List<Employee> empList = EmployeeList();

    //Here Filter the list based on user input;
    List<Employee> listStr = empList.Where(name => name.Name == userInput).ToList();

    //Displaying who are employed in CompanyName=FE.
    foreach (Employee temp in listStr)
    {
        HttpContext.Current.Response.Write(temp.Name + "<br/>");
    }
}

Linq4.jpg

Step 8: Simple Distinct() LINQ getting unique data:

public static void SimpleDistinctLinq()
{
    int[] nums = { 52, 52, 53, 110, 110 };

    //Distinct array.
    nums = nums.Distinct().ToArray();

    foreach (int temp in nums)
    {
        HttpContext.Current.Response.Write(temp + "<br/>");
    }
}

Step 9: Complex Distinct() LINQ: getting unique data

public static void ComplexDistinctLinq()
{
    //Employee collection
    List<Employee> empList = EmployeeList();
    //Adding Duplicate item to list.
    empList.Add(new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" });
            empList.Add(new Employee { ID = 200, Name = "Parthiban", CompanyName = "FE" });

    empList = empList.Distinct(new SelectListItemComparer()).ToList();

    foreach (Employee temp in empList)
    {
        HttpContext.Current.Response.Write(temp.Name + "<br/>");
    }
}

Linq5.jpg

Step 10: Simple Select() LINQ: retrieve the data from the list.

/// <summary>
///
Select which used to convert from one datatype to another.
/// </summary>
public static void SimpleSelect()
{
    //Numeric List.
    List<int> list = GetNumberList();

    //Converts the interger to string.
    List<string> listStr = list.Select(i => i.ToString()).ToList();

    //Print items.
    PrintLis<string>(listStr, "Select Interger values and Convert to String:");
}


Linq6.jpg

Step 11: Anonymous Select() LINQ: retrieve the data form the list.

/// <summary>
///
Used to Get Value and Index by AnonymousType.
/// </summary>
public static void SelectAnonymousType()
{
    List<string> list = GetStringList();

    //Select data with Anonymous select.
    //It Set value in first param and set index in second param.
    //the Compiler will generate an automatic name for Anonymous type.
    var result = list.Select((i, ix) => new { Value = i, Key = ix }).ToList();

    foreach (var val in result)
    {
        string messsage = "Value={0} at Index={1}";

        //Display
        HttpContext.Current.Response.Write(
        string.Format(messsage, val.Value, val.Key) + "<br/>");
    }
}


Linq7.jpg

Step 12: ORDERBY() LINQ: both Ascending and Descending order.

/// <summary>
///
Filters Item based on the condition.
/// </summary>
public static void ComplexOrderBy()
{
    //Employee collection
    List<Employee> empList = EmployeeList();

    //Sort By ascending Order.
    List<Employee> listStr = empList.OrderBy(i => i.Name).ToList();

    HttpContext.Current.Response.Write("Ascending Order:");

    foreach (Employee temp in listStr)
    {
        HttpContext.Current.Response.Write(temp.Name + "<br/>");
    }

    HttpContext.Current.Response.Write("<br/>" + "Descending Order:");

    //Sort by Descending order.
    listStr = empList.OrderByDescending(i => i.Name).ToList();

    foreach (Employee temp in listStr)
    {
        HttpContext.Current.Response.Write(temp.Name + "<br/>");
    }
}


Linq8.jpg

Step 13: Cast() LINQ method – Converts the data to its base type.

public static void CastTypeLinq()
{
    //Employee collection
    List<Employee> empList = EmployeeList();

    //Parsing the Company type from the Employee Type.
    List<Company> comList = empList.Cast<Company>().ToList();

    //Displaying the parsed company list from Emp list.
    foreach (Company temp in comList)
    {
        HttpContext.Current.Response.Write(temp.CompanyName + "<br/>");
    }
}

Linq9.jpg

Step 14: Used string List for demo:

public static List<string> GetStringList()
{
    List<string> list = new List<string>();
    list.Add("Lajapathy");
    list.Add("Sathiya");
    list.Add("Parthiban");
    list.Add("AnandBabu");
    list.Add("Sangita");
    list.Add("Lakshmi");
    return list;
}


Step 15: Simple ToLookup() LINQ method:

public static void SimpleLookup()
{
    List<string> list = GetStringList();

    //Sets KeyValue pair based on the string length.
    ILookup<int, string> lookup = list.ToLookup(i => i.Length);

    HttpContext.Current.Response.Write("String length=7" + "<br/>");

    //Iterates only string length having 7.
    foreach (string temp in lookup[7])
    {
        HttpContext.Current.Response.Write(temp + "<br/>");
    }

    HttpContext.Current.Response.Write("<br/>String length=9" + "<br/>");

    //Iterates only string length having 9.
    foreach (string temp in lookup[9])
    {
        HttpContext.Current.Response.Write(temp + "<br/>");
    }
}

Linq10.jpg

Step 16: Use Employee List for demo:

/// <summary>
///
Employee list
/// </summary>
public static List<Employee> EmployeeList()
{
    List<Employee> emp = new List<Employee>();
    emp.Add(new Employee { ID = 100, Name = "Lajapathy", CompanyName = "FE" });
    emp.Add(new Employee { ID = 200, Name = "Parthiban", CompanyName = "FE" });
    emp.Add(new Employee { ID = 400, Name = "Sathiya", CompanyName = "FE" });
    emp.Add(new Employee { ID = 300, Name = "Anand Babu", CompanyName = "FE" });
    emp.Add(new Employee { ID = 300, Name = "Naveen", CompanyName = "HCL" });
    return emp;
}


Linq11.jpg

Step 17: Complex ToLookup() LINQ method:

public static void AdvaceLookupLookup()
{
    //Employee collection
    List<Employee> empList = EmployeeList();

    HttpContext.Current.Response.Write("Here Key based on ID<br/>");

    //Creating KeyValue pair based on the ID. we can get items based on the ID.
    ILookup<int, Employee> lookList = empList.ToLookup(id => id.ID);

    //Displaying who having the ID=100.
    foreach (Employee temp in lookList[100])
    {
        HttpContext.Current.Response.Write(temp.Name + "<br/>");
    }

    HttpContext.Current.Response.Write("Here Key based on CompanyName<br/>");

    //Creating KeyValue pair based on the CompanyName.
    //we can get items based on the CompanyName.
    ILookup<string, Employee> lookList2 = empList.ToLookup(id => id.CompanyName);

    //Displaying who are employed in CompanyName=FE.
    foreach (Employee temp in lookList2["FE"])
    {
        HttpContext.Current.Response.Write(temp.Name + "<br/>");
    }
}


Step 18: Use collection for Demo:

public static List<int> GetNumberList()
{
    List<int> list = new List<int>();
    list.Add(11);
    list.Add(22);
    list.Add(77);
    list.Add(13);
    list.Add(17);
    list.Add(41);
    return list;
}


Step 19: ALL () LINQ methods:

It is used to check whether the entire item in the list matches the specified condition. If one item fails, it returns false.

        /// <summary>
        /// Just to check whether all element satisfies the given condition or not.
        /// Return just TRUE or FALSE.
        /// It applies to all the DataType like string,datetime etc and also for custom class.
        /// </summary>
        public static void LinqIntALL()
        {
            List<int> list = GetNumberList();
            //It returns bool, check whether all the item in the list greather than 13.
            bool isAll = list.All(i => i > 13);
            //Print
            HttpContext.Current.Response.Write("all greather than 13 :" + isAll + "<br/>");

            //It returns bool, check whether all the item in the list greather than 10.
            isAll = list.All(i => i > 10);
            HttpContext.Current.Response.Write("all greather than 10 :" + isAll + "<br/>");
        }


Linq12.jpg

Step 20: ANY () LINQ Method:

It is used to check whether any item satisfies the given condition. If one item satisfies then it return true otherwise false.

        /// <summary>
        /// Just to check whether all element satisfies the given condition or not.
        /// Return just TRUE or FALSE.
        /// It applies to all the DataType like string,datetime etc and also for custom class.
        /// </summary>
        public static void LinqIntANY()
        {
            List<int> list = GetNumberList();
            //It returns bool, Just to check any element is greater than 13.
            bool isAll = list.Any(i => i > 13);
            //Print
            HttpContext.Current.Response.Write("Any greather than 13 :" + isAll + "<br/>");

            //It returns bool, Just to check any element is equal to 11.
            isAll = list.All(i => i == 10);
            HttpContext.Current.Response.Write("Any equal to 11 :" + isAll + "<br/>");
        }


Linq13.jpg

Step 21: TAKE () LINQ Method:

Used to get the Top "N" items from the list. Note it can be taken in sequencial order.

/// <summary>
///
This is used to take Top 'N' items form the list.Like "Top 5" in sql.
/// </summary>
public static void LinqInTake()
{
    List<int> list = GetNumberList();

    //This takes only the Top two items from the list and eliminate others.
    //"2" in param indicates how much item you need.
    //ToList() helps to convert IEnumerable to List.
    list = list.Take(2).ToList();

    //Print
    PrintLis<int>(list, "Take Only top two item");
}


Step 22: TAKEWHILE () LINQ Method:

Used to take items from list based on the given condition. It iterates sequentially and check each and every item, if condition.

Satisfies then it adds to collection to the specific count.

/// <summary>
///
This is used to take Top 'N' items based on the given condition.
/// </summary>
public static void LinqInTakeWhile()
{
    List<int> list = GetNumberList();

    //This takes item if the element is less than 77 and eliminate others.
    //ToList() helps to convert IEnumerable to List.
    list = list.TakeWhile(i => i < 77).ToList();
    //Print
    PrintLis<int>(list, "Take items less than 77");

    //This takes item if the element is less than 22 and eliminate others.
    //ToList() helps to convert IEnumerable to List.
    list = list.TakeWhile(i => i < 22).ToList();
    //Print
    PrintLis<int>(list, "Take items less than 22");
}

Linq14.jpg

Step 23: SKIP () LINQ Method:

Used to skip the top items based on the given count.

/// <summary>
///
This is used to Skip Top 'N' items form the list.
/// </summary>
public static void LinqInSKIP()
{
    List<int> list = GetNumberList();

    //This SKIPS the Top two items from the list and keep remaining.
    //"2" in param indicates how much item you need to skip.
    //ToList() helps to convert IEnumerable to List.
    list = list.Skip(2).ToList();

    //Print
    PrintLis<int>(list, "Skips top two item");
}


Linq15.jpg

Step 24: SKIPWHILE () LINQ Method:

Used to skip items from the list based on the given condition.

It checks each and every item sequentially and if the condition is true then it skips the item up to the condition turns false.

/// <summary>
///
This is used to Skip Top 'N' items form the list based on the given conditon.
/// </summary>
public static void LinqInSKIPWhile()
{
    List<int> list = GetNumberList();

    //This SKIPS upo the item equals to 11.
    //Sequence check if any item not equal to 11, it return default list.
    //ToList() helps to convert IEnumerable to List.
    list = list.SkipWhile(i => i == 11).ToList();

    //Print
    PrintLis<int>(list, "Skips the item upto it equals to 11");
}

Linq16.jpg

Thanks for reading this article.
 

Next Recommended Readings