Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Deferred Execution in LINQ

Deferred Execution of Query

  class Sample
    {
      public int i;
      public String str;
    }

  static void Main(string[] args)
    {
      List lst = new List();
      lst.Add(new Sample() { i = 1, str = "String1" });
      lst.Add(new Sample() { i = 2, str = "String2" });
      lst.Add(new Sample() { i = 3, str = "String3" });
      lst.Add(new Sample() { i = 4, str = "String4" });
      int a = 1;
      IEnumerable lStr = (from l in lst
                          where l.i == a
                          select l);  //It will just store query in lStr variable.
     }

When we write any LINQ query as mentioned, it doesn't get executed immediately. It actually stores  query in the variable and every time we use/enumerate the variable it executes the query and use the result. It is called deferred execution.

    Sample s = lStr.First();  ///Query will be executed here
    Console.WriteLine(s.str);

So that whenever filter variable(a) changes prior to the use of object(lStr), output will automatically changes.

"if" condition inside Select Clause of LINQ Query.

In LINQ you can't use "if" statement directly in select clause, but you can achieve this by using ternary operator.

Consider you are querying an Array of object & the object internally contains another object. We have to select some field from inner object. But it may be chance that for some cases inner object is null. So to prevent your query from throwing "Object Reference not set to instance of object exception.", you need to check for null object in select clause.

Code:

class Periods
        {
            public int StartYear;
            public int EndYear;
        }



class student
        {
            public int RollNo;
            public string name;
            public DateTime DOB;
            public Periods coursePeriod;
        }



//There is an array of student object which internally contains Periods object.

student[] arrStudents= new student[100];

// You have to fetch list of students and time period spend in college
//code to fill arrStudents Array.
//output object
class studentCousePeriod
        {
            public int Rollno;
            public int StartYear;
            public int EndYear;
        }

LINQ :

Custom / Partial Projection in LINQ to Hashtable / Dictionary

Like SQL we can project partial or custom data in output. In the output of LINQ Query it will be an enumerable collection of anonymous type. This anonymous type is being created by using new operator in the select clause and member fields are generated dynamically in the select new part of the LINQ.

Consider a data dictionary and structure as followed:
public static Dictionary<int, marks> stuResult;
public struct marks
{
   public int m_hindi;
   public int m_english;
   public int m_maths;
}

Consider marks is structure datatype which contains marks details of a student. stuResult Dictionary contains RollNo(int), as key and object of marks as its value. Now we have to find out the Total marks obtained by each students. To find this LINQ will be as:

Where Clause with LINQ to Hashtable / Dictionaries

In this article, we will discuss How can we use where clause in LINQ to Object(Hastable / Dictionaries). Many time  while working with the Dictionaries or Hashtables, we may require to find out the values from them which satisfies some specific criteria. In that case we used to write iterations and then find the values which satisfies the criteria. Maybe writing the loop is a easy task for the beginners, but writing code for checking the values and performing the operations are so boring and tedious task.For the checking the values   for specific criteria we need to declare intermediate variables etc. But by using LINQ, this can be done so easily with few lines of code even without using iterations.

LINQ: Join operations on Hashtables / Dictionaries

In this example we will discuss, how to perform Join operation on dictionaries / hash tables. 
Consider 2 Dictionaries, one dictionary contains Roll No (Int) as key and a Structure (marks) (which contains marks of student) as value. Another dictionary contains Roll No(Int) as key and Name of Student (String) as value. Now we have to find name of students and corresponding marks of the students. 

So in this case we will perform Join on the key of both dictionaries and will have enumerable collection of KeyValue pairs (key will be name of student and value will have marks details) in the query result.

     var QueryResult = from mrks in stuResult.AsEnumerable<KeyValuePair<int, marks>>()
                       join pd in stuPDetails.AsEnumerable<KeyValuePair<int, string>>()
                       on mrks.Key equals pd.Key
                       select new KeyValuePair<String, marks>(pd.Value, mrks.Value);

Above mentioned LINQ query will perform join operation on the key values of the dictionaries. Finally selects the new KeyValue pairs having String(Name of Student) as key, marks(Marks details of the student) as value.

Example of JOIN on Dictionaries

Operations on specific elements of array by using LINQ

Here I am considering count operation has to be performed on array. As we know that if sum of specific elements of array is to be found, then we have to iterate the array and check whether element of the array satisfies the predicate or not. If it satisfies then increase the count else ignore it. But how is it, if I say that we need not to iterate the array to find the count or any such kind of operations.

Consider an integer array (arr is an array for our code) having n elements. we have to find out how many elements are there which are greater than or equals to 75.

Iteration method to find the count

            int count = 0;
            for (int i = 0; i < arr.Length; i++)
                if (arr[i] >= 75) count++;

What, if we can write SQL like query in C# also to perform these kind of operations. LINQ introduced in .net framework 3.5, provides us such facilities.

LINQ for above Operation

Introduction to LINQ

Language INtegrated Query (LINQ) was introduced very 1st with the .Net framework 3.5. it bridges the gap between the world of objects and world of data.
LINQ extends the language by so called query expressions, which looks like a SQL Statement, by which we can extract and process data from array, Enumerable collection of classes, XML documents, MS SQL Tables, third party data sources etc.

List and Details of Query Operators/Keywords of LINQ

1. from: from keyword is used to mention the datasource on which the LINQ is applied..

2. where: The where operator/clause is similar to the where clause in the SQL. It is used to provide the conditions which is to be satisfied. 

3. select:  select operator is used to perform the projection on the collection to select the elements from the collection.

LINQ to Object (Load Dictionary/HashTable from DataTable)

Code to load data of DataTable in the Dictionary object (Considering there atleast one column which is containing unique values).

Consider a dictionary dicDetail which is to be loaded by the values available in a data table. I am considering that a table dtSample is containing 2 columns(RollNo, Name). Now our task is to load the data in the dictionary dicDetail. In which RollNo will be key and Name will be value.

LINQ to OBJECT(HashTable)

Scenario:

A detail class(Marks), which contains Object of a Structure(MarkDetails) as Data Member. There are some member functions like AddorUpdateRecord which is use to update data.
Another class named "MarksInfo" containing HashTable. The HashTable contains the object of class "Marks" as value fields and some key, (Hashtable will have one entry per student).

Requirement: We need to make DataTable that contains marks of all the students.