Explain different types of LINQ with examples.
LINQ (Language Integrated Query)
LINQ (Language Integrated Query) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. With LINQ, a query is a first-class language construct just like classes, methods, events. The LINQ family of technologies provides a consistent query expression experience for objects (LINQ to Objects), relational database CLING to SQL) and XML (LINQ to XML).
Example
class LINQQuery Expressions
{ //Specify data source
static void Main ()
int[] score s = new int[ ] {10, 20, 30, 40}; // Define query expression
Enumercable <int>scoredQuery=from score in scores where score > 20 select score;
//Execuite query
for each (inti in scoreQuery)
{
console.Write(i+" ");
}
}
}
Output 30.40
a) Introduction of LINQ to XML
While using LINQ to XML, loading XML documents into memory is easy and more easier to querying and document modifications. It is also possible to save XML documents existing in memory to dusk and serialize them. LINQ to XML has its power in system.XML.Ling namespace and container all necessary classes.XAttribute ,XCDtata, XComment, XContianer, XName etc.
Eg: Read an XML file using LINQ
using System,
using System. Collections. Generic;
using System. Linq
using System. XML. Linq;
namespace LINQ toXML {
class Example of XML {
static void Main (string[] args) {
String myXML = @" < Student >
<student Name </student>
< student > Age </student>.
<students > Addres </students>
</student>"
XDodument xdoc = new X Document()
xdoc = XDocument· Parse (my XML);
var result = xdoc Element ("student"). Descendants ();
for each (X Element item in result) {
Console. WriteLine ("student Name "+item.value);
}
Console.WriteLine("\Press any key to continue..");
Console.ReadKey();
}
}
}
b)LINQ - Lambola Expression:
The term Lambda expression has derived its name from lambda Calculus which in turn is a mathematical notation applied for defining functions. Lambda is expressed as:
expression as: (Input character parameter) ⇒ Expression or statement block i.e
y=y*y
Ex:
Using System;
Using system. Collections:
using System. Ling;
using System. Text";
namespace Lambdaexample{
class program{
delegare int del(int i)
static void Main(string[] args) {
del my Delegate = y = y*y;
int j = my Delegate(5);
Console. Write.Line (j);
Console. ReadKey();
}
}
}
Comments
Post a Comment