Wednesday, September 5, 2012

Hello All,

Greetings of the day.

Ambrish Jha

9811545125
Hello All,


Greetings of the day.


If you don't know CSS3/JQuery/HTML5 then you are 10 years back in your group.

Ambrish Jha
9811545125

Monday, June 21, 2010

What is Web Services

Top Ten FAQs for Web Services
FAQ from webservices.XML.com by Ethan Cerami

Web services represent an important evolutionary step in building distributed applications. But, what exactly is a Web service? What is the Web service protocol stack? And, does the World Wide Web Consortium support any Web service standards?
Below are answers to the top ten most frequently asked questions (FAQs) about Web services. Together, they provide an overview of the Web services landscape as well as links to additional resources for more in-depth material.

1. What is a Web service?

Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system.
XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications.
Beyond this basic definition, a Web service may also have two additional (and desirable) properties:
  • First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL).
  • Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration.
Web services currently run a wide gamut from news syndication and stock-market data to weather reports and package-tracking systems.


2. What is new about Web services?

People have been using Remote Procedure Calls (RPC) for some time now, and they long ago discovered how to send such calls over HTTP.
So, what is really new about Web services? The answer is XML.
XML lies at the core of Web services, and provides a common language for describing Remote Procedure Calls, Web services, and Web service directories.
Prior to XML, one could share data among different applications, but XML makes this so much easier to do. In the same vein, one can share services and code without Web services, but XML makes it easier to do these as well.
By standardizing on XML, different applications can more easily talk to one another, and this makes software a whole lot more interesting.

3. I keep reading about Web services, but I have never actually seen one. Can you show me a real Web service in action?

If you want a more intuitive feel for Web services, try out the IBM Web Services Browser, available on the IBM Alphaworks site. The browser provides a series of Web services demonstrations. Behind the scenes, it ties together SOAP, WSDL, and UDDI to provide a simple plug-and-play interface for finding and invoking Web services. For example, you can find a stock-quote service, a traffic-report service, and a weather service. Each service is independent, and you can stack services like building blocks. You can, therefore, create a single page that displays multiple services--where the end result looks like a stripped-down version of my.yahoo or my.excite.

4. What is the Web service protocol stack?

The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers:
  • Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP).
  • XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP.
  • Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL.
  • Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI.
Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol stack includes a whole zoo of newer, evolving protocols. These include WSFL (Web Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signature), and USML (UDDI Search Markup Language). For an overview of these protocols, check out Pavel Kulchenko's article, Web Services Acronyms, Demystified, on XML.com.
Fortunately, you do not need to understand the full protocol stack to get started with Web services. Assuming you already know the basics of HTTP, it is best to start at the XML Messaging layer and work your way up.

5. What is XML-RPC?

XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response.
More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls.
Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server.
To get a quick sense of XML-RPC, here is a sample XML-RPC request to a weather service (with the HTTP Headers omitted):


   weather.getWeather
   
      10016
   
The request consists of a simple  element, which specifies the method name (getWeather) and any method parameters (zip code).
Here is a sample XML-RPC response from the weather service:


   
      
         65
      
   
The response consists of a single  element, which specifies the return value (the current temperature). In this case, the return value is specified as an integer.
In many ways, XML-RPC is much simpler than SOAP, and therefore represents the easiest way to get started with Web services.
The official XML-RPC specification is available at XML-RPC.com. Dozens of XML-RPC implementations are available in Perl, Python, Java, and Ruby. See the XML-RPC home page for a complete list of implementations.

6. What is SOAP?

SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another.
To get a quick sense of SOAP, here is a sample SOAP request to a weather service (with the HTTP Headers omitted):


   
      10016
      
   
As you can see, the request is slightly more complicated than XML-RPC and makes use of both XML namespaces and XML Schemas. Much like XML-RPC, however, the body of the request specifies both a method name (getWeather), and a list of parameters (zipcode).
Here is a sample SOAP response from the weather service:

   
      
         65
      
   

The response indicates a single integer return value (the current temperature).
The World Wide Web Consortium (W3C) is in the process of creating a SOAP standard. The latest working draft is designated as SOAP 1.2, and the specification is now broken into two parts. Part 1 describes the SOAP messaging framework and envelope specification. Part 2 describes the SOAP encoding rules, the SOAP-RPC convention, and HTTP binding details.

7. What is WSDL?

The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack.
In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following:
  • Information on all publicly available functions.
  • Data type information for all XML messages.
  • Binding information about the specific transport protocol to be used.
  • Address information for locating the specified service.
WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services.
Below is a sample WSDL file. This file describes the public interface for the weather service used in the SOAP example above. Obviously, there are many details to understanding the example. For now, just consider two points.
    First, the  elements specify the individual XML messages that are transferred between computers. In this case, we have agetWeatherRequest and a getWeatherResponse. Second, the  element specifies that the service is available via SOAP and is available at a specific URL.


   
      
   
   
      
   

   
      
         
         
      
   
   
   
      
      
         
         
            
         
         
            
         
      
   

   
      WSDL File for Weather Service
      
         
      
   
Using WSDL, a client can locate a Web service, and invoke any of the publicly available functions. With WSDL-aware tools, this process can be entirely automated, enabling applications to easily integrate new services with little or no manual code. For example, check out the GLUE platform from the Mind Electric.
WSDL has been submitted to the W3C, but it currently has no official status within the W3C. See this W3C page for the latest draft.

8. What is UDDI?

UDDI (Universal Description, Discovery, and Integration) currently represents the discovery layer within the Web services protocol stack.
UDDI was originally created by Microsoft, IBM, and Ariba, and represents a technical specification for publishing and finding businesses and Web services.
At its core, UDDI consists of two parts.
  • First, UDDI is a technical specification for building a distributed directory of businesses and Web services. Data is stored within a specific XML format, and the UDDI specification includes API details for searching existing data and publishing new data.
  • Second, the UDDI Business Registry is a fully operational implementation of the UDDI specification. Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data. It also enables any company to register themselves and their services.
The data captured within UDDI is divided into three main categories:
  • White Pages: This includes general information about a specific company. For example, business name, business description, and address.
  • Yellow Pages: This includes general classification data for either the company or the service offered. For example, this data may include industry, product, or geographic codes based on standard taxonomies.
  • Green Pages: This includes technical information about a Web service. Generally, this includes a pointer to an external specification, and an address for invoking the Web service.
You can view the Microsoft UDDI site, or the IBM UDDI site. The complete UDDI specification is available at uddi.org.
Beta versions of UDDI Version 2 are available at:

9. How do I get started with Web Services?

The easiest way to get started with Web services is to learn XML-RPC. Check out the XML-RPC specification

10. Does the W3C support any Web service standards?

The World Wide Web Consortium (W3C) is actively pursuing standardization of Web service protocols. In September 2000, the W3C established anXML Protocol Activity. The goal of the group is to establish a formal standard for SOAP. A draft version of SOAP 1.2 is currently under review, and progressing through the official W3C recommendation process.
On January 25, 2002, the W3C also announced the formation of a Web Service Activity. This new activity will include the current SOAP work as well as two new groups. The first new group is the Web Services Description Working Group, which will take up work on WSDL. The second new group is the Web Services Architecture Working Group, which will attempt to create a cohesive framework for Web service protocols.

Wednesday, February 24, 2010


LINQ

LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.

.NET Language-Integrated Query

After two decades, the industry has reached a stable point in the evolution of object-oriented (OO) programming technologies. Programmers now take for granted features like classes, objects, and methods. In looking at the current and next generation of technologies, it has become apparent that the next big challenge in programming technology is to reduce the complexity of accessing and integrating information that is not natively defined using OO technology. The two most common sources of non-OO information are relational databases and XML.
Rather than add relational or XML-specific features to our programming languages and runtime, with the LINQ project we have taken a more general approach and are adding general-purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data. This facility is called .NET Language-Integrated Query (LINQ).
We use the term language-integrated query to indicate that query is an integrated feature of the developer's primary programming languages (for example, Visual C#, Visual Basic). Language-integrated query allows query expressions to benefit from the rich metadata, compile-time syntax checking, static typing and IntelliSense that was previously available only to imperative code. Language-integrated query also allows a single general purpose declarative query facility to be applied to all in-memory information, not just information from external sources.
.NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable-based information source. LINQ allows third parties to augment the set of standard query operators with new domain-specific operators that are appropriate for the target domain or technology. More importantly, third parties are also free to replace the standard query operators with their own implementations that provide additional services such as remote evaluation, query translation, optimization, and so on. By adhering to the conventions of the LINQ pattern, such implementations enjoy the same language integration and tool support as the standard query operators.
The extensibility of the query architecture is used in the LINQ project itself to provide implementations that work over both XML and SQL data. The query operators over XML (LINQ to XML) use an efficient, easy-to-use, in-memory XML facility to provide XPath/XQuery functionality in the host programming language. The query operators over relational data (LINQ to SQL) build on the integration of SQL-based schema definitions into the common language runtime (CLR) type system. This integration provides strong typing over relational data while retaining the expressive power of the relational model and the performance of query evaluation directly in the underlying store.

Getting Started with Standard Query Operators

To see language-integrated query at work, we'll begin with a simple C# 3.0 program that uses the standard query operators to process the contents of an array:
using System;
using System.Linq;
using System.Collections.Generic;

class app {
  static void Main() {
    string[] names = { "Burke", "Connor", "Frank", 
                       "Everett", "Albert", "George", 
                       "Harris", "David" };

    IEnumerable query = from s in names 
                               where s.Length == 5
                               orderby s
                               select s.ToUpper();

    foreach (string item in query)
      Console.WriteLine(item);
  }
}
If you were to compile and run this program, you'd see this as output:
BURKE
DAVID
FRANK
To understand how language-integrated query works, we need to dissect the
 first statement of our program.
IEnumerable query = from s in names 
                           where s.Length == 5
                           orderby s
                           select s.ToUpper();
The local variable query is initialized with a query expression. A query expression operates on one or more information sources by applying one or more query operators from either the standard query operators or domain-specific operators. This expression uses three of the standard query operators: WhereOrderBy, and Select.
Visual Basic 9.0 supports LINQ as well. Here's the preceding statement written in Visual Basic 9.0:
Dim query As IEnumerable(Of String) = From s in names _
                                     Where s.Length = 5 _
                   Order By s _
                   Select s.ToUpper()
Both the C# and Visual Basic statements shown here use query expressions. Like the foreach statement, query expressions are convenient declarative shorthand over code you could write manually. The statements above are semantically identical to the following explicit syntax shown in C#:
IEnumerable query = names 
                            .Where(s => s.Length == 5) 
                            .OrderBy(s => s)
                            .Select(s => s.ToUpper());
This form of query is called a method-based query. The arguments to the WhereOrderBy, and Select operators are called lambda expressions, which are fragments of code much like delegates. They allow the standard query operators to be defined individually as methods and strung together using dot notation. Together, these methods form the basis for an extensible query language.

Language Features Supporting the LINQ Project

LINQ is built entirely on general purpose language features, some of which are new to C# 3.0 and Visual Basic 9.0. Each of these features has utility on its own, yet collectively these features provide an extensible way to define queries and queryable APIs. In this section we explore these language features and how they contribute to a much more direct and declarative style of queries.

Lambda Expressions and Expression Trees

Many query operators allow the user to provide a function that performs filtering, projection, or key extraction. The query facilities build on the concept of lambda expressions, which provide developers with a convenient way to write functions that can be passed as arguments for subsequent evaluation. Lambda expressions are similar to CLR delegates and must adhere to a method signature defined by a delegate type. To illustrate this, we can expand the statement above into an equivalent but more explicit form using the Func delegate type:
Func   filter  = s => s.Length == 5;
Func extract = s => s;
Func project = s => s.ToUpper();

IEnumerable query = names.Where(filter) 
                                 .OrderBy(extract)
                                 .Select(project);
Lambda expressions are the natural evolution of anonymous methods in C# 2.0. For example, we could have written the previous example using anonymous methods like this:
Func   filter  = delegate (string s) {
                                   return s.Length == 5; 
                               };

Func extract = delegate (string s) { 
                                   return s; 
                               };

Func project = delegate (string s) {
                                   return s.ToUpper(); 
                               };

IEnumerable query = names.Where(filter) 
                                 .OrderBy(extract)
                                 .Select(project);
In general, the developer is free to use named methods, anonymous methods, or lambda expressions with query operators. Lambda expressions have the advantage of providing the most direct and compact syntax for authoring. More importantly, lambda expressions can be compiled as either code or data, which allows lambda expressions to be processed at runtime by optimizers, translators, and evaluators.
The namespace System.Linq.Expressions defines a distinguished generic type, Expression, which indicates that an expression tree is desired for a given lambda expression rather than a traditional IL-based method body. Expression trees are efficient in-memory data representations of lambda expressions and make the structure of the expression transparent and explicit.
The determination of whether the compiler will emit executable IL or an expression tree is determined by how the lambda expression is used. When a lambda expression is assigned to a variable, field, or parameter whose type is a delegate, the compiler emits IL that is identical to that of an anonymous method. When a lambda expression is assigned to a variable, field, or parameter whose type is Expression for some delegate type T, the compiler emits an expression tree instead.
For example, consider the following two variable declarations:
Func             f = n => n < 5;
Expression> e = n => n < 5;
The variable f is a reference to a delegate that is directly executable:
bool isSmall = f(2); // isSmall is now true
The variable e is a reference to an expression tree that is not directly executable:
bool isSmall = e(2); // compile error, expressions == data
Unlike delegates, which are effectively opaque code, we can interact with the expression tree just like any other data structure in our program.
Expression> filter = n => n < 5;

BinaryExpression    body  = (BinaryExpression)filter.Body;
ParameterExpression left  = (ParameterExpression)body.Left;
ConstantExpression  right = (ConstantExpression)body.Right;

Console.WriteLine("{0} {1} {2}", 
                  left.Name, body.NodeType, right.Value);
The above example decomposes the expression tree at runtime and prints the following string:
n LessThan 5
This ability to treat expressions as data at runtime is critical to enable an ecosystem of third-party libraries that leverage the base query abstractions that are part of the platform. The LINQ to SQL data access implementation leverages this facility to translate expression trees to T-SQL statements suitable for evaluation in the store.

Extension Methods

Lambda expressions are one important piece of the query architecture. Extension methods are another. Extension methods combine the flexibility of "duck typing" made popular in dynamic languages with the performance and compile-time validation of statically-typed languages. With extension methods third parties may augment the public contract of a type with new methods while still allowing individual type authors to provide their own specialized implementation of those methods.
Extension methods are defined in static classes as static methods, but are marked with the[System.Runtime.CompilerServices.Extension] attribute in CLR metadata. Languages are encouraged to provide a direct syntax for extension methods. In C#, extension methods are indicated by the this modifier which must be applied to the first parameter of the extension method. Let's look at the definition of the simplest query operator, Where:
namespace System.Linq {
  using System;
  using System.Collections.Generic;

  public static class Enumerable {
    public static IEnumerable Where(
             this IEnumerable source,
             Func predicate) {

      foreach (T item in source)
        if (predicate(item))
          yield return item;
    }
  }
}
The type of the first parameter of an extension method indicates what type the extension applies to. In the example above, the Where extension method extends the type IEnumerable. Because Where is a static method, we can invoke it directly just like any other static method:
IEnumerable query = Enumerable.Where(names, 
                                          s => s.Length < 6);
However, what makes extension methods unique is that they can also be invoked using instance syntax:
IEnumerable query = names.Where(s => s.Length < 6);
Extension methods are resolved at compile-time based on which extension methods are in scope. When a namespace is imported with a using statement in C# or an Import statement in Visual Basic, all extension methods that are defined by static classes from that namespace are brought into scope.
The standard query operators are defined as extension methods in the type System.Linq.Enumerable. When examining the standard query operators, you'll notice that all but a few of them are defined in terms of theIEnumerable interface. This means that every IEnumerable-compatible information source gets the standard query operators simply by adding the following using statement in C#:
using System.Linq; // makes query operators visible
Users who want to replace the standard query operators for a specific type may either: define their own same-named methods on the specific type with compatible signatures, or define new same-named extension methods that extend the specific type. Users who want to eschew the standard query operators altogether can simply not put System.Linq into scope and write their own extension methods for IEnumerable.
Extension methods are given the lowest priority in terms of resolution and are only used if there is no suitable match on the target type and its base types. This allows user-defined types to provide their own query operators that take precedence over the standard operators. For example, consider the following custom collection:
public class MySequence : IEnumerable {
  public IEnumerator GetEnumerator() {
    for (int i = 1; i <= 10; i++) 
      yield return i; 
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator(); 
  }

  public IEnumerable Where(Func filter) {
    for (int i = 1; i <= 10; i++) 
      if (filter(i)) 
        yield return i;
  }
}
Given this class definition, the following program will use the MySequence.Where implementation, not the extension method, as instance methods take precedence over extension methods:
MySequence s = new MySequence();
foreach (int item in s.Where(n => n > 3))
    Console.WriteLine(item);
The OfType operator is one of the few standard query operators that doesn't extend an IEnumerable-based information source. Let's look at the OfType query operator:
public static IEnumerable OfType(this IEnumerable source) {
  foreach (object item in source) 
    if (item is T) 
      yield return (T)item;
}
OfType accepts not only IEnumerable-based sources, but also sources that are written against the non-parameterized IEnumerable interface that was present in version 1.0 of the .NET Framework. The OfType operator allows users to apply the standard query operators to classic .NET collections like this:
// "classic" cannot be used directly with query operators
IEnumerable classic = new OlderCollectionType();

// "modern" can be used directly with query operators
IEnumerable modern = classic.OfType();
In this example, the variable modern yields the same sequence of values as does classic. However, its type is compatible with modern IEnumerable code, including the standard query operators.
The OfType operator is also useful for newer information sources, as it allows filtering values from a source based on type. When producing the new sequence, OfType simply omits members of the original sequence that are not compatible with the type argument. Consider this simple program that extracts strings from a heterogeneous array:
object[] vals = { 1, "Hello", true, "World", 9.1 };
IEnumerable justStrings = vals.OfType();
When we enumerate the justStrings variable in a foreach statement, we'll get a sequence of two strings: "Hello" and "World."

Deferred Query Evaluation

Observant readers may have noted that the standard Where operator is implemented using the yield construct introduced in C# 2.0. This implementation technique is common for all the standard operators that return sequences of values. The use of yield has an interesting benefit which is that the query is not actually evaluated until it is iterated over, either with a foreach statement or by manually using the underlying GetEnumerator and MoveNext methods. This deferred evaluation allows queries to be kept as IEnumerable-based values that can be evaluated multiple times, each time yielding potentially different results.
For many applications, this is exactly the behavior that is desired. For applications that want to cache the results of query evaluation, two operators, ToList and ToArray, are provided that force the immediate evaluation of the query and return either a List or an array containing the results of the query evaluation.
To see how deferred query evaluation works consider this program that runs a simple query over an array:
// declare a variable containing some strings
string[] names = { "Allen", "Arthur", "Bennett" };

// declare a variable that represents a query
IEnumerable ayes = names.Where(s => s[0] == 'A');

// evaluate the query
foreach (string item in ayes) 
  Console.WriteLine(item);

// modify the original information source
names[0] = "Bob";

// evaluate the query again, this time no "Allen"
foreach (string item in ayes) 
    Console.WriteLine(item);
The query is evaluated each time the variable ayes is iterated over. To indicate that a cached copy of the results is needed, we can simply append a ToList or ToArray operator to the query like this:
// declare a variable containing some strings
string[] names = { "Allen", "Arthur", "Bennett" };

// declare a variable that represents the result
// of an immediate query evaluation
string[] ayes = names.Where(s => s[0] == 'A').ToArray();

// iterate over the cached query results
foreach (string item in ayes) 
    Console.WriteLine(item);

// modifying the original source has no effect on ayes
names[0] = "Bob";

// iterate over result again, which still contains "Allen"
foreach (string item in ayes)
    Console.WriteLine(item);
Both ToArray and ToList force immediate query evaluation. The same is true for the standard query operators that return singleton values (for example: FirstElementAtSumAverageAllAny).

The IQueryable Interface

The same deferred execution model is usually desired for data sources that implement the query functionality by using expression trees, such as LINQ to SQL. These data sources can benefit from implementing the IQueryableinterface for which all the query operators required by the LINQ pattern are implemented by using expression trees. Each IQueryable has a representation of "the code needed to run the query" in the form of an expression tree. All the deferred query operators return a new IQueryable that augments that expression tree with a representation of a call to that query operator. Thus, when it becomes time to evaluate the query, typically because the IQueryableis enumerated, the data source can process the expression tree representing the whole query in one batch. As an example, a complicated LINQ to SQL query obtained by numerous calls to query operators may result in only a single SQL query getting sent to the database.
The benefit for data source implementers of reusing this deferring functionality by implementing the IQueryableinterface is obvious. To the clients who write the queries, on the other hand, it is a great advantage to have a common type for remote information sources. Not only does it allow them to write polymorphic queries that can be used against different sources of data, but it also opens up the possibility for writing queries that go across domains.

Initializing Compound Values

Lambda expressions and extension methods provide us with everything we need for queries that simply filter members out of a sequence of values. Most query expressions also perform projection over those members, effectively transforming members of the original sequence into members whose value and type may differ from the original. To support writing these transforms, LINQ relies on a new construct called object initializers to create new instances of structured types. For the rest of this document, we'll assume the following type has been defined:
public class Person {
  string name;
  int age;
  bool canCode;

  public string Name {
    get { return name; } set { name = value; }
  }

  public int Age {
    get { return age; } set { age = value; }
  }

  public bool CanCode {
    get { return canCode; } set { canCode = value; }
  }
}
Object initializers allow us to easily construct values based on the public fields and properties of a type. For example, to create a new value of type Person, we can write this statement:
Person value = new Person {
    Name = "Chris Smith", Age = 31, CanCode = false
};
Semantically, this statement is equivalent to the following sequence of statements:
Person value = new Person();
value.Name = "Chris Smith";
value.Age = 31;
value.CanCode = false;
Object initializers are an important feature for language-integrated query, as they allow the construction of new structured values in contexts where only expressions are allowed (such as within lambda expressions and expression trees). For example, consider this query expression that creates a new Person value for each value in the input sequence:
IEnumerable query = names.Select(s => new Person {
    Name = s, Age = 21, CanCode = s.Length == 5
});
Object initialization syntax is also convenient for initializing arrays of structured values. For example, consider this array variable that is initialized using individual object initializers:
static Person[] people = {
  new Person { Name="Allen Frances", Age=11, CanCode=false },
  new Person { Name="Burke Madison", Age=50, CanCode=true },
  new Person { Name="Connor Morgan", Age=59, CanCode=false },
  new Person { Name="David Charles", Age=33, CanCode=true },
  new Person { Name="Everett Frank", Age=16, CanCode=true },
};

Structured Values and Types

The LINQ project supports a data-centric programming style in which some types exist primarily to provide a static "shape" over a structured value rather than a full-blown object with both state and behavior. Taking this premise to its logical conclusion, it is often the case that all the developer cares about is the structure of the value, and the need for a named type for that shape is of little use. This leads to the introduction of anonymous types that allow new structures to be defined "inline" with their initialization.
In C#, the syntax for anonymous types is similar to the object initialization syntax except that the name of the type is omitted. For example, consider the following two statements:
object v1 = new Person {
    Name = "Brian Smith", Age = 31, CanCode = false
};

object v2 = new { // note the omission of type name
    Name = "Brian Smith", Age = 31, CanCode = false
};
The variables v1 and v2 both point to an in-memory object whose CLR type has three public properties NameAge, and CanCode. The variables differ in that v2 refers to an instance of an anonymous type. In CLR terms, anonymous types are no different than any other type. What makes anonymous types special is that they have no meaningful name in your programming language. The only way to create instances of an anonymous type is using the syntax shown above.
To allow variables to refer to instances of anonymous types yet still benefit from static typing, C# introduces implicitly typed local variables: The var keyword may be used in place of the type name for local variable declarations. For example, consider this legal C# 3.0 program:
var s = "Bob";
var n = 32;
var b = true;
The var keyword tells the compiler to infer the type of the variable from the static type of the expression used to initialize the variable. In this example, the types of sn, and b are stringint, and bool, respectively. This program is identical to the following:
string s = "Bob";
int    n = 32;
bool   b = true;
The var keyword is a convenience for variables whose types have meaningful names, but it is a necessity for variables that refer to instances of anonymous types.
var value = new { 
  Name = " Brian Smith", Age = 31, CanCode = false
};
In the example above, variable value is of an anonymous type whose definition is equivalent to the following pseudo-C#:
internal class ??? {
  string _Name;
  int    _Age;
  bool   _CanCode;

  public string Name { 
    get { return _Name; } set { _Name = value; }
  }

  public int Age{ 
    get { return _Age; } set { _Age = value; }
  }

  public bool CanCode { 
    get { return _CanCode; } set { _CanCode = value; }
  }

  public bool Equals(object obj) { ... }

  public bool GetHashCode() { ... }
}
Anonymous types cannot be shared across assembly boundaries; however, the compiler ensures that there is at most one anonymous type for a given sequence of property name/type pairs within each assembly.
Because anonymous types are often used in projections to select one or more members of an existing structured value, we can simply reference fields or properties from another value in the initialization of an anonymous type. This results in the new anonymous type getting a property whose name, type, and value are all copied from the referenced property or field.
For instance, consider this example that creates a new structured value by combining properties from other values:
var bob = new Person { Name = "Bob", Age = 51, CanCode = true };
var jane = new { Age = 29, FirstName = "Jane" };

var couple = new {
    Husband = new { bob.Name, bob.Age },
    Wife = new { Name = jane.FirstName, jane.Age }
};

int    ha = couple.Husband.Age; // ha == 51
string wn = couple.Wife.Name;   // wn == "Jane"
The referencing of fields or properties shown above is simply a convenient syntax for writing the following more explicit form:
var couple = new {
    Husband = new { Name = bob.Name, Age = bob.Age },
    Wife = new { Name = jane.FirstName, Age = jane.Age }
};
In both cases, the couple variable gets its own copy of the Name and Age properties from bob and jane.
Anonymous types are most often used in the select clause of a query. For example, consider the following query:
var query = people.Select(p => new { 
               p.Name, BadCoder = p.Age == 11
           });

foreach (var item in query) 
  Console.WriteLine("{0} is a {1} coder", 
                     item.Name,
                     item.BadCoder ? "bad" : "good");
In this example, we were able to create a new projection over the Person type that exactly matched the shape we needed for our processing code yet still gave us the benefits of a static type.

More Standard Query Operators

On top of the basic query facilities described above, a number of operators provide useful ways of manipulating sequences and composing queries, giving the user a high degree of control over the result within the convenient framework of the standard query operators.

Sorting and Grouping

In general, the evaluation of a query results in a sequence of values that are produced in some order that is intrinsic in the underlying information sources. To give developers explicit control over the order in which these values are produced, standard query operators are defined for controlling the order. The most basic of these operators is theOrderBy operator.
The OrderBy and OrderByDescending operators can be applied to any information source and allow the user to provide a key extraction function that produces the value that is used to sort the results. OrderBy andOrderByDescending also accept an optional comparison function that can be used to impose a partial order over the keys. Let's look at a basic example:
string[] names = { "Burke", "Connor", "Frank", "Everett", 
                   "Albert", "George", "Harris", "David" };

// unity sort
var s1 = names.OrderBy(s => s); 
var s2 = names.OrderByDescending(s => s);

// sort by length
var s3 = names.OrderBy(s => s.Length); 
var s4 = names.OrderByDescending(s => s.Length);
The first two query expressions produce new sequences that are based on sorting the members of the source based on string comparison. The second two queries produce new sequences that are based on sorting the members of the source based on the length of each string.
To allow multiple sort criteria, both OrderBy and OrderByDescending return OrderedSequence rather than the generic IEnumerable. Two operators are defined only on OrderedSequence, namely ThenBy andThenByDescending which apply an additional (subordinate) sort criterion. ThenBy/ThenByDescending themselves return OrderedSequence, allowing any number of ThenBy/ThenByDescending operators to be applied:
string[] names = { "Burke", "Connor", "Frank", "Everett", 
                   "Albert", "George", "Harris", "David" };

var s1 = names.OrderBy(s => s.Length).ThenBy(s => s);
Evaluating the query referenced by s1 in this example would yield the following sequence of values:
"Burke", "David", "Frank", 
"Albert", "Connor", "George", "Harris", 
"Everett"
In addition to the OrderBy family of operators, the standard query operators also include a Reverse operator.Reverse simply enumerates over a sequence and yields the same values in reverse order. Unlike OrderByReversedoesn't consider the actual values themselves in determining the order, rather it relies solely on the order the values are produced by the underlying source.
The OrderBy operator imposes a sort order over a sequence of values. The standard query operators also include theGroupBy operator, which imposes a partitioning over a sequence of values based on a key extraction function. TheGroupBy operator returns a sequence of IGrouping values, one for each distinct key value that was encountered. AnIGrouping is an IEnumerable that additionally contains the key that was used to extract its contents:
public interface IGrouping : IEnumerable {
  public K Key { get; }
}
The simplest application of GroupBy looks like this:
string[] names = { "Albert", "Burke", "Connor", "David",
                   "Everett", "Frank", "George", "Harris"};

// group by length
var groups = names.GroupBy(s => s.Length);

foreach (IGrouping group in groups) {
    Console.WriteLine("Strings of length {0}", group.Key);

    foreach (string value in group)
        Console.WriteLine("  {0}", value);
}    
When run, this program prints out the following:
Strings of length 6
  Albert
  Connor
  George
  Harris
Strings of length 5
  Burke
  David
  Frank
Strings of length 7
  Everett
A la SelectGroupBy allows you to provide a projection function that is used to populate members of the groups.
string[] names = { "Albert", "Burke", "Connor", "David",
                   "Everett", "Frank", "George", "Harris"};

// group by length
var groups = names.GroupBy(s => s.Length, s => s[0]);
foreach (IGrouping group in groups) {
    Console.WriteLine("Strings of length {0}", group.Key);

    foreach (char value in group)
        Console.WriteLine("  {0}", value);
}  
This variation prints the following:
Strings of length 6
  A
  C
  G
  H
Strings of length 5
  B
  D
  F
Strings of length 7
  E
Note   From this example that the projected type does not need to be the same as the source. In this case, we created a grouping of integers to characters from a sequence of strings.

Aggregation Operators

Several standard query operators are defined for aggregating a sequence of values into a single value. The most general aggregation operator is Aggregate, which is defined like this:
public static U Aggregate(this IEnumerable source, 
                                U seed, Func func) {
  U result = seed;

  foreach (T element in source) 
      result = func(result, element);

  return result;
}
The Aggregate operator makes it simple to perform a calculation over a sequence of values. Aggregate works by calling the lambda expression once for each member of the underlying sequence. Each time Aggregate calls the lambda expression, it passes both the member from the sequence and an aggregated value (the initial value is the seed parameter to Aggregate). The result of the lambda expression replaces the previous aggregated value, andAggregate returns the final result of the lambda expression.
For example, this program uses Aggregate to accumulate the total character count over an array of strings:
string[] names = { "Albert", "Burke", "Connor", "David",
                   "Everett", "Frank", "George", "Harris"};

int count = names.Aggregate(0, (c, s) => c + s.Length);
// count == 46
In addition to the general purpose Aggregate operator, the standard query operators also include a general purposeCount operator and four numeric aggregation operators (MinMaxSum, and Average) that simplify these common aggregation operations. The numeric aggregation functions work over sequences of numeric types (for example, int,doubledecimal) or over sequences of arbitrary values as long as a function is provided that projects members of the sequence into a numeric type.
This program illustrates both forms of the Sum operator just described:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
string[] names = { "Albert", "Burke", "Connor", "David",
                   "Everett", "Frank", "George", "Harris"};

int total1 = numbers.Sum();            // total1 == 55
int total2 = names.Sum(s => s.Length); // total2 == 46
Note   The second Sum statement is equivalent to the previous example using Aggregate.

Select vs. SelectMany

The Select operator requires the transform function to produce one value for each value in the source sequence. If your transform function returns a value that is itself a sequence, it is up to the consumer to traverse the sub-sequences manually. For example, consider this program that breaks strings into tokens using the existing String.Split method:
string[] text = { "Albert was here", 
                  "Burke slept late", 
                  "Connor is happy" };

var tokens = text.Select(s => s.Split(' '));

foreach (string[] line in tokens)
    foreach (string token in line)
        Console.Write("{0}.", token);
When run, this program prints out the following text:
Albert.was.here.Burke.slept.late.Connor.is.happy.
Ideally, we would have liked our query to have returned a coalesced sequence of tokens and not exposed the intermediate string[] to the consumer. To achieve this, we use the SelectMany operator instead of the Selectoperator. The SelectMany operator works similarly to the Select operator. It differs in that the transform function is expected to return a sequence that is then expanded by the SelectMany operator. Here's our program rewritten usingSelectMany:
string[] text = { "Albert was here", 
                  "Burke slept late", 
                  "Connor is happy" };

var tokens = text.SelectMany(s => s.Split(' '));

foreach (string token in tokens)
    Console.Write("{0}.", token);
The use of SelectMany causes each intermediate sequence to be expanded as part of normal evaluation.
SelectMany is ideal for combining two information sources:
string[] names = { "Burke", "Connor", "Frank", "Everett", 
                   "Albert", "George", "Harris", "David" };

var query = names.SelectMany(n => 
                     people.Where(p => n.Equals(p.Name))
                 );
In the lambda expression passed to SelectMany, the nested query applies to a different source, but has in scope the nparameter passed in from the outer source. Thus people.Where is called once for each n, with the resulting sequences flattened by SelectMany for the final output. The result is a sequence of all the people whose name appears in thenames array.

Join Operators

In an object oriented program, objects that are related to each other will typically be linked with object references which are easy to navigate. The same usually does not hold true for external information sources, where data entries often have no option but to "point" to each other symbolically, with IDs or other data that can uniquely identify the entity pointed to. The concept of joins refers to the operation of bringing the elements of a sequence together with the elements they "match up with" from another sequence.
The previous example with SelectMany actually does exactly that, matching up strings with people whose names are those strings. However, for this particular purpose, the SelectMany approach isn't very efficient—it will loop through all the elements of people for each and every element of names. By bringing all the information of this scenario—the two information sources and the "keys" by which they are matched up—together in one method call, the Join operator is able to do a much better job:
string[] names = { "Burke", "Connor", "Frank", "Everett", 
                   "Albert", "George", "Harris", "David" };

var query = names.Join(people, n => n, p => p.Name, (n,p) => p);
This is a bit of a mouthful, but see how the pieces fit together: The Join method is called on the "outer" data source,names. The first argument is the "inner" data source, people. The second and third arguments are lambda expressions to extract keys from the elements of the outer and inner sources, respectively. These keys are what the Join method uses to match up the elements. Here we want the names themselves to match the Name property of the people. The final lambda expression is then responsible for producing the elements of the resulting sequence: It is called with each pair of matching elements n and p, and is used to shape the result. In this case we choose to discard the n and return the p. The end result is the list of Person elements of people whose Name is in the list of names.
A more powerful cousin of Join is the GroupJoin operator. GroupJoin differs from Join in the way the result-shaping lambda expression is used: Instead of being invoked with each individual pair of outer and inner elements, it will be called only once for each outer element, with a sequence of all of the inner elements that match that outer element. To make that concrete:
string[] names = { "Burke", "Connor", "Frank", "Everett", 
                   "Albert", "George", "Harris", "David" };

var query = names.GroupJoin(people, n => n, p => p.Name,                   
                 (n, matching) => 
                      new { Name = n, Count = matching.Count() }
);
This call produces a sequence of the names you started out with paired with the number of people who have that name. Thus, the GroupJoin operator allows you to base your results on the whole "set of matches" for an outer element.

Query Syntax

The existing foreach statement in C# provides a declarative syntax for iteration over the .NET FrameworksIEnumerable/IEnumerator methods. The foreach statement is strictly optional, but it has proven to be a very convenient and popular language mechanism.
Building on this precedent, query expressions simplifies queries with a declarative syntax for the most common query operators: WhereJoinGroupJoinSelectSelectManyGroupByOrderByThenByOrderByDescending,ThenByDescending, and Cast.
Let's start by looking at the simple query we began this paper with:
IEnumerable query = names 
                            .Where(s => s.Length == 5) 
                            .OrderBy(s => s)
                            .Select(s => s.ToUpper());
Using a query expression we can rewrite this exact statement like this:
IEnumerable query = from s in names 
                            where s.Length == 5
                            orderby s
                            select s.ToUpper();
Like the foreach statement in C#, query expressions are more compact and easier to read, but are completely optional. Every expression that can be written as a query expression has a corresponding (albeit more verbose) syntax using dot notation.
Let's begin by looking at the basic structure of a query expression. Every syntactic query expression in C# begins with afrom clause and ends with either a select or group clause. The initial from clause can be followed by zero or morefromletwherejoin and orderby clauses. Each from clause is a generator that introduces a range variable over a sequence; each let clause gives a name to the result of an expression; and each where clause is a filter that excludes items from the result. Every join clause correlates a new data source with the results of the preceding clauses. Anorderby clause specifies an ordering for the result:
query-expression ::= from-clause query-body

query-body ::= 

      query-body-clause* final-query-clause query-continuation?

query-body-clause ::=
  (from-clause 
      | join-clause 
      | let-clause 
      | where-clause 
      | orderby-clause)

from-clause ::= from itemName in srcExpr

join-clause ::= join itemName in srcExpr on keyExpr equals keyExpr 
       (into itemName)?

let-clause ::= let itemName = selExpr

where-clause ::= where predExpr

orderby-clause ::= orderby (keyExpr (ascending | descending)?)*

final-query-clause ::=
  (select-clause | groupby-clause)

select-clause ::= select selExpr

groupby-clause ::= group selExpr by keyExpr

query-continuation ::= into itemName query-body
For example, consider these two query expressions:
var query1 = from p in people
             where p.Age > 20
             orderby p.Age descending, p.Name
             select new { 
                 p.Name, Senior = p.Age > 30, p.CanCode
             };

var query2 = from p in people
             where p.Age > 20
             orderby p.Age descending, p.Name
             group new { 
                p.Name, Senior = p.Age > 30, p.CanCode
             } by p.CanCode;
The compiler treats these query expressions as if they were written using the following explicit dot-notation:
var query1 = people.Where(p => p.Age > 20)
                   .OrderByDescending(p => p.Age)
                   .ThenBy(p => p.Name)
                   .Select(p => new { 
                       p.Name, 
                       Senior = p.Age > 30, 
                       p.CanCode
                   });

var query2 = people.Where(p => p.Age > 20)
                   .OrderByDescending(p => p.Age)
                   .ThenBy(p => p.Name)
                   .GroupBy(p => p.CanCode, 
                            p => new {
                                   p.Name, 
                                   Senior = p.Age > 30, 
                                   p.CanCode
                   });
Query expressions undergo a mechanical translation into calls of methods with specific names. The exact query operatorimplementation that is chosen therefore depends both on the type of the variables being queried and the extension methods that are in scope.
The query expressions shown so far have only used one generator. When more than one generator is used, each subsequent generator is evaluated in the context of its predecessor. For example, consider this slight modification to our query:
var query = from s1 in names 
            where s1.Length == 5
            from s2 in names 
            where s1 == s2
            select s1 + " " + s2;
When run against this input array:
string[] names = { "Burke", "Connor", "Frank", "Everett", 
                   "Albert", "George", "Harris", "David" };
we get the following results:
Burke Burke
Frank Frank
David David
The query expression above expands to this dot-notation expression:
var query = names.Where(s1 => s1.Length == 5)
                 .SelectMany(s1 => names, (s1,s2) => new {s1,s2})
                 .Where($1 => $1.s1 == $1.s2) 
                 .Select($1 => $1.s1 + " " + $1.s2);
Note   This version of SelectMany takes an extra lambda expression which is used to produce the result based on elements from the outer and inner sequences. In this lambda expression, the two range variables are collected in an anonymous type. The compiler invents a variable name $1 to denote that anonymous type in subsequent lambda expressions.
A special kind of generator is the join clause, which will introduce elements of another source that match up with the elements of the preceding clauses according to given keys. A join clause may yield the matching elements one by one, but if specified with an into clause, the matching elements will be given as a group:
var query = from n in names
            join p in people on n equals p.Name into matching
            select new { Name = n, Count = matching.Count() };
Not surprisingly, this query expands quite directly into one we have seen before:
var query = names.GroupJoin(people, n => n, p => p.Name,                   
            (n, matching) => 
                      new { Name = n, Count = matching.Count() }
);
It is often useful to treat the results of one query as a generator in a subsequent query. To support this, query expressions use the into keyword to splice a new query expression after a select or group clause. This is called a query continuation.
The into keyword is especially useful for post-processing the results of a group by clause. For example, consider this program:
var query = from item in names
            orderby item
            group item by item.Length into lengthGroups
            orderby lengthGroups.Key descending
            select lengthGroups;

foreach (var group in query) { 
    Console.WriteLine("Strings of length {0}", group.Key);

    foreach (var val in group)
        Console.WriteLine("  {0}", val);
}
This program outputs the following:
Strings of length 7
  Everett
Strings of length 6
  Albert
  Connor
  George
  Harris
Strings of length 5
  Burke
  David
  Frank
In this section it was described how C# implements query expressions. Other languages may elect to support additional query operators with explicit syntax, or not to have query expressions at all.
It is important to note that the query syntax is by no means hard-wired to the standard query operators. It is a purely syntactic feature that applies to anything which fulfills the query pattern by implementing underlying methods with the appropriate names and signatures. The standard query operators described above do so by using extension methods to augment the IEnumerable interface. Developers may exploit the query syntax on any type they wish, as long as they make sure that it adheres to the query pattern, either by direct implementation of the necessary methods or by adding them as extension methods.
This extensibility is exploited in the LINQ project itself by the provision of two LINQ-enabled API's, namely LINQ to SQL, which implements the LINQ pattern for SQL-based data access, and LINQ to XML which allows LINQ queries over XML data. Both of these are described in the following sections.

LINQ to SQL: SQL Integration

.NET Language-Integrated Query can be used to query relational data stores without leaving the syntax or compile-time environment of the local programming language. This facility, code-named LINQ to SQL, takes advantage of the integration of SQL schema information into CLR metadata. This integration compiles SQL table and view definitions into CLR types that can be accessed from any language.
LINQ to SQL defines two core attributes, [Table] and [Column], which indicate which CLR types and properties correspond to external SQL data. The [Table] attribute can be applied to a class and associates the CLR type with a named SQL table or view. The [Column] attribute can be applied to any field or property and associates the member with a named SQL column. Both attributes are parameterized to allow SQL-specific metadata to be retained. For example, consider this simple SQL schema definition:
create table People (
    Name nvarchar(32) primary key not null, 
    Age int not null, 
    CanCode bit not null
)

create table Orders (
    OrderID nvarchar(32) primary key not null, 
    Customer nvarchar(32) not null, 
    Amount int
)
The CLR equivalent looks like this:
[Table(Name="People")]
public class Person {
  [Column(DbType="nvarchar(32) not null", Id=true)]
  public string Name; 

  [Column]
  public int Age;

  [Column]
  public bool CanCode;
}

[Table(Name="Orders")]
public class Order {
  [Column(DbType="nvarchar(32) not null", Id=true)]
  public string OrderID; 

  [Column(DbType="nvarchar(32) not null")]        
  public string Customer; 

  [Column]
  public int? Amount; 
}
Note   This example that nullable columns map to nullable types in the CLR (nullable types first appeared in version 2.0 of the .NET Framework), and that for SQL types that don't have a 1:1 correspondence with a CLR type (for example, nvarcharchartext), the original SQL type is retained in the CLR metadata.
To issue a query against a relational store, the LINQ to SQL implementation of the LINQ pattern translates the query from its expression tree form into a SQL expression and ADO.NET DbCommand object suitable for remote evaluation. For example, consider this simple query:
// establish a query context over ADO.NET sql connection
DataContext context = new DataContext(
     "Initial Catalog=petdb;Integrated Security=sspi");

// grab variables that represent the remote tables that 
// correspond to the Person and Order CLR types
Table custs = context.GetTable();
Table orders   = context.GetTable();

// build the query
var query = from c in custs
            from o in orders
            where o.Customer == c.Name
            select new { 
                       c.Name, 
                       o.OrderID,
                       o.Amount,
                       c.Age
            }; 

// execute the query
foreach (var item in query) 
    Console.WriteLine("{0} {1} {2} {3}", 
                      item.Name, item.OrderID, 
                      item.Amount, item.Age);
The DataContext type provides a lightweight translator that translates the standard query operators to SQL.DataContext uses the existing ADO.NET IDbConnection for accessing the store and can be initialized with either an established ADO.NET connection object or a connection string that can be used to create one.
The GetTable method provides IEnumerable-compatible variables that can be used in query expressions to represent the remote table or view. Calls to GetTable do not cause any interaction with the database—rather they represent the potential to interact with the remote table or view using query expressions. In our example above, the query does not get transmitted to the store until the program iterates over the query expression, in this case using the foreachstatement in C#. When the program first iterates over the query, the DataContext machinery translates the expression tree into the following SQL statement that is sent to the store:
SELECT [t0].[Age], [t1].[Amount], 
       [t0].[Name], [t1].[OrderID]
FROM [Customers] AS [t0], [Orders] AS [t1]
WHERE [t1].[Customer] = [t0].[Name]
It's important to note that by building query capability directly into the local programming language, developers get the full power of the relational model without having to statically bake the relationships into the CLR type. That stated, comprehensive object/relational mapping can also take advantage of this core query capability for users that want that functionality. LINQ to SQL provides object-relational mapping functionality with which the developer can define and navigate relationships between objects. You can refer to Orders as a property of the Customer class using mapping, so that you do not need explicit joins to tie the two together. External mapping files allow the mapping to be separated from the object model for richer mapping capabilities.

LINQ to XML: XML Integration

.NET Language-Integrated Query for XML (LINQ to XML) allows XML data to be queried by using the standard query operators as well as tree-specific operators that provide XPath-like navigation through descendants, ancestors, and siblings. It provides an efficient in-memory representation for XML that integrates with the existing System.Xmlreader/writer infrastructure and is easier to use than W3C DOM. There are three types that do most of the work of integrating XML with queries: XNameXElement and XAttribute.
XName provides an easy-to-use way to deal with the namespace-qualified identifiers (QNames) used as both element and attribute names. XName handles the efficient atomization of identifiers transparently and allows either symbols or plain strings to be used wherever a QName is needed.
XML elements and attributes are represented using XElement and XAttribute respectively. XElement and XAttributesupport normal construction syntax, allowing developers to write XML expressions using a natural syntax:
var e = new XElement("Person", 
                     new XAttribute("CanCode", true),
                     new XElement("Name", "Loren David"),
                     new XElement("Age", 31));

var s = e.ToString();
This corresponds to the following XML:

  Loren David 
  31 
Notice that no DOM-based factory pattern was needed to create the XML expression, and that the ToStringimplementation yielded the textual XML. XML elements can also be constructed from an existing XmlReader or from a string literal:
var e2 = XElement.Load(xmlReader);
var e1 = XElement.Parse(
@"
  Loren David
  31
");
XElement also supports emitting XML using the existing XmlWriter type.
XElement dovetails with the query operators, allowing developers to write queries against non-XML information and produce XML results by constructing XElements in the body of a select clause:
var query = from p in people 
            where p.CanCode
            select new XElement("Person", 
                                  new XAttribute("Age", p.Age),
                                  p.Name);
This query returns a sequence of XElements. To allow XElements to be built out of the result of this kind of query, theXElement constructor allows sequences of elements to be passed as arguments directly:
var x = new XElement("People",
                  from p in people 
                  where p.CanCode
                  select 
                    new XElement("Person", 
                                   new XAttribute("Age", p.Age),
                                   p.Name));
This XML expression results in the following XML:

  Allen Frances 
  Connor Morgan 
The statement above has a direct translation to Visual Basic. However, Visual Basic 9.0 also supports the use of XML literals, which allow query expressions to be expressed using a declarative XML syntax directly from Visual Basic. The previous example could be constructed with the Visual Basic statement:
Dim x = _
        
             >p.Name _
             %>
        
The examples so far have shown how to construct new XML values using language-integrated query. The XElement andXAttribute types also simplify the extraction of information from XML structures. XElement provides accessor methods that allow query expressions to be applied to the traditional XPath axes. For example, the following query extracts just the names from the XElement shown above:
IEnumerable justNames =
    from e in x.Descendants("Person")
    select e.Value;

//justNames = ["Allen Frances", "Connor Morgan"]
To extract structured values from the XML, we simply use an object initializer expression in our select clause:
IEnumerable persons =
    from e in x.Descendants("Person")
    select new Person { 
        Name = e.Value,
        Age = (int)e.Attribute("Age") 
    };
Note that both XAttribute and XElement support explicit conversions to extract the text value as a primitive type. To deal with missing data, we can simply cast to a nullable type:
IEnumerable persons =
    from e in x.Descendants("Person")
    select new Person { 
        Name = e.Value,
        Age = (int?)e.Attribute("Age") ?? 21
    };
In this case, we use a default value of 21 when the Age attribute is missing.
Visual Basic 9.0 provides direct language support for the ElementsAttribute, and Descendants accessor methods ofXElement, allowing XML-based data to be accessed using a more compact and direct syntax called XML axis properties. We can use this functionality to write the preceding C# statement like this:
Dim persons = _
      From e In x... _   
      Select new Person { _
          .Name = e.Value, _
          .Age = IIF(e.@Age, 21) _
      } 
In Visual Basic, x... gets all items in the Descendants collection of x with the name Person, while the expression e.@Age finds all the XAttributes with the name AgeThe Value property gets the first attribute in the collection and calls the Value property on that attribute.

Summary

.NET Language-Integrated Query adds query capabilities to the CLR and the languages that target it. The query facility builds on lambda expressions and expression trees to allow predicates, projections, and key extraction expressions to be used as opaque executable code or as transparent in-memory data suitable for downstream processing or translation. The standard query operators defined by the LINQ project work over any IEnumerable-based information source, and are integrated with ADO.NET (LINQ to SQL) and System.Xml (LINQ to XML) to allow relational and XML data to gain the benefits of language-integrated query.
Standard Query Operators in a Nutshell
OperatorDescription
WhereRestriction operator based on predicate function
Select/SelectManyProjection operators based on selector function
Take/Skip/ TakeWhile/SkipWhilePartitioning operators based on position or predicate function
Join/GroupJoinJoin operators based on key selector functions
ConcatConcatenation operator
OrderBy/ThenBy/OrderByDescending/ThenByDescendingSorting operators sorting in ascending or descending order based on optional key selector and comparer functions
ReverseSorting operator reversing the order of a sequence
GroupByGrouping operator based on optional key selector and comparer functions
DistinctSet operator removing duplicates
Union/IntersectSet operators returning set union or intersection
ExceptSet operator returning set difference
AsEnumerableConversion operator to IEnumerable
ToArray/ToListConversion operator to array or List
ToDictionary/ToLookupConversion operators to Dictionary orLookup (multi-dictionary) based on key selector function
OfType/CastConversion operators to IEnumerable based on filtering by or conversion to type argument
SequenceEqualEquality operator checking pairwise element equality
First/FirstOrDefault/Last/LastOrDefault/Single/SingleOrDefaultElement operators returning initial/final/only element based on optional predicate function
ElementAt/ElementAtOrDefaultElement operators returning element based on position
DefaultIfEmptyElement operator replacing empty sequence with default-valued singleton sequence
RangeGeneration operator returning numbers in a range
RepeatGeneration operator returning multiple occurrences of a given value
EmptyGeneration operator returning an empty sequence
Any/AllQuantifier checking for existential or universal satisfaction of predicate function
ContainsQuantifier checking for presence of a given element
Count/LongCountAggregate operators counting elements based on optional predicate function
Sum/Min/Max/AverageAggregate operators based on optional selector functions
AggregateAggregate operator accumulating multiple values based on accumulation function and optional seed


Ambrish Jha
9811545125