Thursday, January 26, 2012

LINQ

What is LINQ?
It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C# , VB.NET. 
 
Why can not datareader by returned from a Web Services Method?
Because, it is not serializable 
 
What is the extension of the file, when LINQ to SQL is used?
The extension of the file is .dbml 
 
How LINQ is beneficial than Stored Procedures?
There are couple of advantage of LINQ over stored procedures.
1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception! 
 
What is a Lambda expression?
A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements. Lambda expressions can be used mostly to create delegates or expression tree types. Lambda expression uses lambda operator => and read as 'goes to' operator.
Left side of this operator specifies the input parameters and contains the expression or statement block at the right side.
    Example: myExp = myExp/10;   
Now, let see how we can assign the above to a delegate and create an expression tree:
    delegate int myDel(int intMyNum);
    static void Main(string[] args)
    {
        //assign lambda expression to a delegate:
        myDel myDelegate = myExp => myExp / 10;
        int intRes = myDelegate(110);
        Console.WriteLine("Output {0}", intRes);
        Console.ReadLine();
       
        //Create an expression tree type
        //This needs System.Linq.Expressions
        Expression<myDel> myExpDel = myExp => myExp /10;
    }

No te:
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where. 
 
What is the LINQ file extension that interacts with Code Behind objects.
its .dbml
 
Why Select clause comes after from clause in LINQ?
The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’s why from clause must appear before Select in LINQ. 
 
Difference between LINQ and Stored Procedures?
There are couple of advantage of LINQ over stored procedures.
1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.
2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!
4. PreCompiled - Stored Procedures are precompiled, and LINQ queries need to compile before execution. So stored procedures are fast in performance. 
 
What are Benefits and Advantages of LINQ?
Benefits and Advantages of LINQ are:
1. Makes it easier to transform data into objects.
2. A common syntax for all data.
3. Strongly typed code.
4. Provider integration.
5. Reduction in work.
6. Performance in the general case doesn't become an issue.
7. Built-in security.
8. LINQ is declarative.
 
What are the three main components of LINQ or Language INtegrated Query?
1. Standard Query Operators
2. Language Extensions
3. LINQ Providers
 
How are Standard Query Operators implemented in LINQ?
Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable<t> interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable<t>. Also, most of the generic collection classes implement IEnumerable<t> interface.

How are Standard Query Operators useful in LINQ?
Standard Query Operators in LINQ can be used for working with collections for any of the following and more.
1. Get total count of elements in a collection.
2. Order the results of a collection.
3. Grouping.
4. Computing average.
5. Joining two collections based on matching keys.
6. Filter the results 
 
List the important language extensions made in C# to make LINQ a reality?
1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions 
 
What is the purpose of LINQ Providers in LINQ?
LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source. 
 
What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.
 
Write a program using LINQ to find the sum of first 5 prime numbers?
    class Program
    {
        static void Main()
        {
            int[] MyPrimeNumbers = {1,2,3,5,7};
            // Use the Count() and Sum() Standard Query Operators to
            // compute the count and total sum respectively
            Concole.WriteLine("The sum of first {0} prime number is {1}",
                MyPrimeNumbers.Count(), MyPrimeNumbers.Sum());
        }
    }    
 
What is Difference between XElement and XDocument?
Both are the classes defined by System.Xml.Linq namespace
XElement class represents an XML fragment
XDocument class represents an entire XML document with all associated meta-data.
example:     XDocument d = new XDocument(
        new XComment("hello"),
        new XElement("book",
                     new XElement("bookname", "ASP.NET"),
                     new XElement("authorname", "techmedia"),
                    ) );
 
What are Quantifiers?
They are LINQ Extension methods which return a Boolean value
1) All
2) Any
3) Contains
4) SequenceEqual
example:
int[] arr={10,20,30};
var b=arr.All(a=>a>20);
-------------------------------------------
Output:
b will return False since all elements are not > 20. 
 
What is the benefit of using LINQ on Dataset?
The main aim of using LINQ to Dataset is to run strongly typed queries on Dataset.
Suppose we want to combine the results from two Datasets, or we want to take a distinct value from the Dataset, then it is advisable to use LINQ.
Normally you can use the SQL queries to run on the database to populate the Dataset, but you are not able to use SQL query on a Dataset to retrieve a particular values. To get this you need to use ADO.NET functionalities. But, in case of LINQ, it provides more dignified way of querying the Dataset and provides some new features as compared to ADO.NET. 
 
Which class's extension methods are used in LINQ to SQL?
1. System.Linq.Enumerable

2. System.Linq.Queryable
3. None of these 
 
Which assembly represents the core LINQ API?
System.Query.dll assembly represents the core LINQ API.
 
What is the use of System.Data.DLinq.dll?
System.Data.DLinq.dll provides functionality to work with LINQ to SQL. 
 
What is the use of System.XML.XLinq.dll?
System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML. 
 
Why can't datareader be returned from a Web Service's Method
Because datareader is not serializable. 
 
What is the LINQ file extension that interacts with Code Behind's objects?
The extension of the file is .dbml 
 
Why Select clause comes after from clause in LINQ?
The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’s why from clause must appear before Select in LINQ.

What is Linq to SQL Deferred Loading?
(C#) - Deferred Loading is a property of Linq to sql, by default it is set true,
Example – Let’s have two tables -
Blogs Table (BlogID ,Blog Name,owner) and Post table ( PostID, BlogID, Title, Body)
To find Name and No’s of posts in each blog:
    BlogDataContext ctx = new BlogDataContext( );
    var query = from b in ctx.Blogs select b;
    foreach (Blog b in query)
    {
        Console.WriteLine("{0} has {1} posts", b.BlogName,
            b.Posts.Count);
    }
   
Output of queries Produce Blog name with no’s of post, But For each Blog Looping will be occurs (in case long list of blogs) that’s reduces Overall Performance that’s called the Deferred loading. 
 
Write a Program using Skip and Take operators. How can it beneficial for bulky data accessing on page?
“skip” and “take” Operator used for Paging. Suppose we have Customer table of 100 records. To find 10 records by skipping the first 50 records from customer table-
    Public void Pagingdatasource ()
    {
        Var Query = from CusDetails in db.customer skip (50) Take (10)
        ObjectDumper.Write(q)
    }
   
Hence The LinQ “ SKIP” operator lets you skip the results you want, and “Take” Operator enables you yo select the rest of result . So By Using Skip and Take Operator, You can create paging of Specific sequence.
 
Write a Program for Concat to create one sequence of Data Rows that contains DataTables's Data Rows, one after the other.
(C#)
    Public void Datasetlinq()
    {
        var numbersA = TestDS.Tables("NumbersA").AsEnumerable();
        var numbersB = TestDS.Tables("NumbersB").AsEnumerable();
        var allNumbers = numbersA.Concat(numbersB);
        Console.WriteLine("All numbers from both arrays:");
        foreach (object n_loopVariable in allNumbers)
        {
            n = n_loopVariable;
            Console.WriteLine(n["number"]);
        }
    }

How can you find average of student marks from student tables (Columns are StudentID, Marks)?
(C#)
    Public void LinqToSqlAverage()
    {
        var query = (from p in db. student. Marks).Average();
        Console.WriteLine(q);
    }

What is “OfType” in linq?
    public void TypeofExa()
    {
        Var numbers = {null,1.0,"two", 3,"four",5,"six",7.0 };
        var doubles = from n in numbers where n is doublen;
        Console.WriteLine("Numbers stored as doubles:");
        foreach (object d in doubles)
        {
            Console.WriteLine(d);
        }
    }

Output:
Numbers stored as doubles:
1
 
How can we find Sequence of Items in two different array (same Type) in the same order using linq query?
    Public void MatchSequenceLinq()
    {
        Var wordsA = {"Rahul","ashok","sweta"};
        Var wordsB = {"rahul","ashok","sweta"};
        var match = wordsA.SequenceEqual(wordsB);
        Console.WriteLine("The sequences match: {0}", match);
    }

Output Result: True 
 
Differentiate between Conversion Operator “IEnumerable” and “ToDictionary” of LINQ.
IEnumerable and To Dictionary both are Conversion Operator which are used to solved to conversion type Problems.
“AsEnumerable ” operator simply returns the source sequence as an object of type IEnumerable. This kind of “conversion on the fly” makes it possible to call the general-purpose extension methods over source, even if its type has specific implementations of them
Signature:
    public static IEnumerable<T> AsEnumerable<T>
    (
        this IEnumerable<T> source
    );
   
“ToDictionary ” Conversion Operator is the instance of Dictionary (k,T) . The “keySelector ”predicate identifies the key of each item while “elementSelector ”, if provided, is used to extract each single item.
Key and elementSelector Predicate can be Used in following ways-
Example-
    Public void ToDictionatyExample()
    {
        Var scoreRecords=
        {
            new {Name = "Alice",Score = 50 },
            new {Name = "Bob",Score = 40 },
            new {Name = "Cathy", Score = 45}
        };
        Var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
        Console.WriteLine("Bob's score: {0}", scoreRecordsDict("Bob"));
    }

Result: Bob's score: { Name = Bob, Score = 40 } 
 
List out the Data Context Functions. Where do we use “SubmitChanges()”?
Create Database ()
Delete database ()
Database Exist ()
Submit Changes ()
Create Query()
Log()
SubmitChanges() - SunbmitChanges Data Context Fuction Used to submit any update to the actual database. 
 
Why do we use “Contains” method for strings type functions?
Contains method Used to find all matching records From Given string using Matching keywords.
Example-
This Examples returns the Customer Names from Customer tables whose Names have contains “Anders”
    Public void LinqToSqlStringUsingContains()
    {
        Var q = From c In db.Customers _
        Where c.ContactName.Contains("Anders") _
        Select c
        ObjectDumper.Write(q)
    }

Partition following list of numbers by their remainder when divided by “3” - { Var numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0} }
(VB)
    Public Sub PartitioningExample()
        Dim numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}

        Dim numberGroups = From n In numbers Group n By key = n _
        Mod 3 Into Group Select Remainder = key, NumberGroup = Group

        For Each g In numberGroups
            Console.WriteLine("Numbers with a remainder of {0} when
                divided by 3:", g.Remainder)
            For Each n In g.NumberGroup
                Console.WriteLine(n)
            Next
        Next
    End Sub

Can you Concat two arrays to create one sequence that contains each array's values, one after the other?
Var ArrayA[]={4,8,7,9,4,7}
Var ArraB[] ={8,2,5,7,8,1}
(VB)
    Public Sub ConcatenateTwoArray()
        Dim numbersA() = {4, 8, 7, 9, 4, 7}
        Dim numbersB() = {8, 2, 5, 7, 8,1}

        Dim allNumbers = numbersA.Concat(numbersB)

        Console.WriteLine("All numbers from both arrays:")
       
        For Each n In allNumbers
            Console.WriteLine(n)
        Next
    End Sub

Output:{4,8,7,9,4,7,8,2,5,7,8,1}
 
Write small Program to generate Xml Document from table like (StudentRecord Table) using LINQ Query.
    Public void CreateXmlDocFromArray()
    {
        // Now enumerate over the array to build an XElement.
        XElement StudentRecords =
            new XElement("StudentInfo",
                            from c in Student select new XElement("Student",
                            new XAttribute("Name", c.Name),
                            new XElement("RollNo", c.RollNo)
                        )
        );
        Console.WriteLine(StudentRecords);
    }

What is Quantifiers in reference linq to Dataset?
Quantifier Operators return the Boolean value (either True or false) if some or all the elements in a sequence satisfy a condition,
Mainly two Quantifiers in linq:
  • Any
  • All
Examples (vb)

"Any" to determine if any of the words in the array contain the substring
    Public Sub ExampleAny()
        Dim words() = {"believe", "relief", "receipt", "field"}
        Dim iAfterE = words.Any(Function(w) w.Contains("ei"))
        Console.WriteLine("There is a word that contains in the
            list that contains 'ei': {0}", iAfterE)
    End Sub
   
Result:
There is a word that contains in the list that contains 'ei': True

"All" to return a grouped a list of products only for categories that have all of their products in stock
    Public Sub Quantifier_All_Exam()
        Dim products = GetProductList()
        Dim productGroups = From p In products _
        Group p By p.Category Into Group _
        Where (Group.All(Function(p) p.UnitsInStock > 0)) _
        Select Category, ProductGroup = Group
        ObjectDumper.Write(productGroups, 1)
    End Sub

No comments: