X

Subscribe To Our Mailing List

P.S I will never spam you...100% GUARANTEED!

Thursday, June 19, 2014

Linq and lambda expressions in c#

Introduction

LINQ or Language Integrated Query is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
LINQ simplifes and reduces the code with neat and effective way. It provides an easy way to write queries that can run with the in-memory objects.
Linq is always associated with Lambda Expressions. in .NET 2.0 we had the concept of Annonymous Methods that allows you to write function body inline without the need of writing a delegate function. So In .Net 3.5 Lambda Expressions are used for the same purpose.
Linq and lambda expressions in c#
Types of LINQ
There are basically 3 types they are -
1. LINQ (Linq to Objects)
2. DLINQ (Linq to SQL)
3. XLINQ (Linq to XML)
How to use
So you will be thinking now in which scenarios i can use it. Here i am going to explain few scenarios where LINQ simplifies the process.
Following are some of the scenarios where we can use LINQ or Lambda expressions -
1) DataTable to List of Objects
Add one method to get the data table for our testing purpose. Since i love to use MVC i will create an MVC application but you can create webform as well.
 private DataTable GetDataTable()
  {
      DataTable dt = new DataTable();
      dt.Columns.Add("ID", typeof(int));
      dt.Columns.Add("Name", typeof(string));
      dt.Columns.Add("Gender", typeof(string));

      DataRow dr1 = dt.NewRow();
      dr1["ID"] = 1;
      dr1["Name"] = "aa";
      dr1["Gender"] = "M";

      DataRow dr2 = dt.NewRow();
      dr2["ID"] = 2;
      dr2["Name"] = "bb";
      dr2["Gender"] = "M";

      DataRow dr3 = dt.NewRow();
      dr3["ID"] = 3;
      dr3["Name"] = "cc";
      dr3["Gender"] = "F";

      dt.Rows.Add(dr1);
      dt.Rows.Add(dr2);
      dt.Rows.Add(dr3);
      
      return dt;
  }



Now i will create one class which same properties as Datatable columns. I will call it as “Employee”.
public int ID { get; set; }

public string Name { get; set; }
        
public string Gender { get; set; }

I will add one more method which uses the DataTable and converts into List of Employees using Reflection -
private IList ConvertToList(DataTable dt)
 {

   var columns = dt.Columns.Cast()
                .Select(c => c.ColumnName)
                .ToList();
    
    var props = typeof(T).GetProperties();
       return dt.AsEnumerable().Select(row =>
       {
          var objT = Activator.CreateInstance();
          foreach (var pro in props)
          {
               if (columns.Contains(pro.Name))
               {
                    if (row[pro.Name] != DBNull.Value)
                    {
                        pro.SetValue(objT, row[pro.Name], null);
                    }
                    else
                    {
                        pro.SetValue(objT, null, null);
                    }
                }
           }
    
        return objT;
    }).ToList();
            
 }

So Call the method like this -
DataTable dt = GetDataTable();
List employees = ConvertToList(dt).ToList();

2) Get DISTINCT List of Objects
Now lets see how we can get distinct records of employees based on employee name using LINQ.

//Get Distinct Employees
List distinctItems = employees.GroupBy(a => a.Name).Select(b => b.First()).ToList();

3) Check value exists in List of Objects
Below is the query to check the value exists in List of Objects or not. If it exists then it will return "true" else "false".

//Check for Employee Name in List of Employees
bool isRes = employees.Any(w => w.Name.Contains("er"));

Hope this helps.

Thank You.



No comments:

Post a Comment

Comments Section