Wednesday 17 December 2014

LINQ Query Example.

Where Clause
To retrieve a list of accounts where the Name contains “Bhimsen”. 

var ListName = from a in DataContext.Account
                    where a.Name.Contains("Bhimsen")
                    select a;
 foreach (var a in ListName)
 {
  System.Console.WriteLine(a.Name);
 }

To retrieve a list of accounts where the Name contains “Bhimsen” and Address is “New Delhi”.

 var ListNameAdd = from a in DataContext.Account
                    where a.Name.Contains(“Bhimsen")
                    where a.Address1 == "Redmond"
                    select a;

 foreach (var a in ListNameAdd)
 {
  System.Console.WriteLine(a.Name + " " + a.Address1);
 }

Equals Operator
To retrieve a list of contacts where the Name is “Bhimsen”

 var LstEql = from c in DataContext.ContactSet
                     where c.Name.Equals("Bhimsen")
                     select new
                     {
                      c.Name,
                      c.Address1
                     };
 foreach (var c in LstEql)
 {
  System.Console.WriteLine(c.Name + " " + c.Address1_City);
 }

To retrieve a list of contacts where the FamilyStatusCode is 3. This corresponds to the Marital Status option of Divorced.
 var LstEql = from c in DataContext.Contact
                     where c.FamilyStatusCode.Equals(3)
                     select new
                     {
                      c.FirstName,
                      c.LastName,
                      c.Address1
                     };
 foreach (var c in LstEql)
 {
  System.Console.WriteLine(c.FirstName +" " + c.LastName);
 }

Not Equals Operator
To retrieve a list of contacts where the Address is not “Bhagalpur”.

 var NtEql = from c in DataContext.Contact
                 where c.Address != "Bhagalpur"
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1
                 };
 foreach (var c in NtEql)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName + " " +
  c.Address1_City);
 }

And , another example :

 var query_ne2 = from c in svcContext.ContactSet
                 where !c.FirstName.Equals("Colin")
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };

 foreach (var c in query_ne2)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }

Distinct Operator
To retrieve a distinct list of contact names. Although there may be duplicates, each name will be listed only once.

 var DistName = (from c in DataContext.Contact
                       select c.Name).Distinct();
 foreach (var c in DistName)
 {
  System.Console.WriteLine(c);
 }
}

Join and Simple Where Clause
To retrieve the account Name and the contact Name where the account Name contains “Kumar” and the contact Name contains “Bhimsen” and the contact is the Primary Contact for the account.

 var LstJoin = from c in DataContext.Contact
                    join a in DataContext.Account
                    on c.ContactId equals a.PrimaryContactId.Id
                    where a.Name.Contains("Kumar")
                    where c.LastName.Contains("Bhimsen")
                    select new
                    {
                     account_name = a.Name,
                     contact_name = c.LastName
                    };

 foreach (var c in LstJoin)
 {
  System.Console.WriteLine(c.account_name)
 }

Simple Inner Join
To retrieve information about an account and the contact listed as the primary contact for the account.

 var query_join1 = from c in svcContext.ContactSet
                   join a in svcContext.AccountSet
                  on c.ContactId equals a.PrimaryContactId.Id
                   select new
                   {
                    c.FullName,
                    c.Address1_City,
                    a.Name,
                    a.Address1_Name
                   };
 foreach (var c in query_join1)
 {
  System.Console.WriteLine("acct: " +
   c.Name +
   "\t\t\t" +
   "contact: " +
   c.FullName);
 }

Self Join
To retrieve information about accounts where an account is the parent account for an account.

var query_join5 = from a in svcContext.AccountSet
                   join a2 in svcContext.AccountSet
                   on a.ParentAccountId.Id equals a2.AccountId

                   select new
                   {
                    account_name = a.Name,
                    account_city = a.Address1_City
                   };
 foreach (var c in query_join5)
 {
  System.Console.WriteLine(c.account_name + "  " + c.account_city);
 }
}

Double and Multiple Joins
The following sample shows how to retrieve information from account, contact and lead where the contact is the primary contact for the account and the lead was the originating lead for the account.

 var query_join4 = from a in svcContext.AccountSet
                   join c in svcContext.ContactSet
                   on a.PrimaryContactId.Id equals c.ContactId
                   join l in svcContext.LeadSet
                   on a.OriginatingLeadId.Id equals l.LeadId
                   select new
                   {
                    contact_name = c.FullName,
                    account_name = a.Name,
                    lead_name = l.FullName
                   };
 foreach (var c in query_join4)
 {
  System.Console.WriteLine(c.contact_name +
   "  " +
   c.account_name +
   "  " +
   c.lead_name);
 }

The following sample shows how to retrieve account and contact information where an account is the parent account for an account and the contact is the primary contact for the account.
 var query_join6 = from c in svcContext.ContactSet
                   join a in svcContext.AccountSet
                   on c.ContactId equals a.PrimaryContactId.Id
                   join a2 in svcContext.AccountSet
                   on a.ParentAccountId.Id equals a2.AccountId
                   select new
                   {
                    contact_name = c.FullName,
                    account_name = a.Name
                   };
 foreach (var c in query_join6)
 {
  System.Console.WriteLine(c.contact_name + "  " + c.account_name);
 }


Join Using Entity Fields
The following sample shows how to retrieve information about accounts from a list

 var list_join = (from a in svcContext.AccountSet
                  join c in svcContext.ContactSet
                  on a.PrimaryContactId.Id equals c.ContactId
                  where a.Name == "Contoso Ltd" &&
                  a.Address1_Name == "Contoso Pharmaceuticals"
                  select a).ToList();
 foreach (var c in list_join)
 {
  System.Console.WriteLine("Account " + list_join[0].Name
      + " and it's primary contact "
      + list_join[0].PrimaryContactId.Id);
 }

Late-Binding Left Join
The following sample shows a left join. A left join is designed to return parents with and without children from two sources. There is a correlation between parent and child, but no child may actually exist.

 var query_join8 = from a in svcContext.AccountSet
                   join c in svcContext.ContactSet
                   on a.PrimaryContactId.Id equals c.ContactId
                   into gr
                   from c_joined in gr.DefaultIfEmpty()
                   select new
                   {
                    contact_name = c_joined.FullName,
                    account_name = a.Name
                   };
 foreach (var c in query_join8)
 {
  System.Console.WriteLine(c.contact_name + "  " + c.account_name);
 }

Greater Than Operator
The following sample shows how to retrieve a list of contacts with an Anniversary date later than February 5, 2010.

 var query_gt1 = from c in svcContext.ContactSet
                 where c.Anniversary > new DateTime(2010, 2, 5)
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };

 foreach (var c in query_gt1)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }


The following sample shows how to retrieve contacts with a CreditLimit greater than $20,000.

 var query_gt2 = from c in svcContext.ContactSet
                 where c.CreditLimit.Value > 20000
                 select new
                 {
                  c.FirstName,
                  c.LastName,
                  c.Address1_City
                 };
 foreach (var c in query_gt2)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.LastName + " " + c.Address1_City);
 }

Greater Than or Equals and Less Than or Equals Operators
The following sample shows how to retrieve contacts with a CreditLimit greater than $200 and less than $400.

 var query_gele1 = from c in svcContext.ContactSet
                   where c.CreditLimit.Value >= 200 &&
                   c.CreditLimit.Value <= 400
                   select new
                   {
                    c.FirstName,
                    c.LastName
                   };
 foreach (var c in query_gele1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

Contains Operator
The following sample shows how to retrieve contacts where the Description contains “Alpine”.
 var query_contains1 = from c in svcContext.ContactSet
                       where c.Description.Contains("Alpine")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_contains1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }


Not Contain Operator
The following sample shows how to retrieve contacts where the Description does not contain “Coho”.

 var query_contains2 = from c in svcContext.ContactSet
                       where !c.Description.Contains("Coho")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_contains2)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

StartsWith and EndsWith Operators
The following sample shows how to retrieve contacts where FirstName starts with “Bri”.

 var query_startswith1 = from c in svcContext.ContactSet
                         where c.FirstName.StartsWith("Bri")
                         select new
                         {
                          c.FirstName,
                          c.LastName
                         };
 foreach (var c in query_startswith1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

The following sample shows how to retrieve contacts where LastName ends with “cox”.
 var query_endswith1 = from c in svcContext.ContactSet
                       where c.LastName.EndsWith("cox")
                       select new
                       {
                        c.FirstName,
                        c.LastName
                       };
 foreach (var c in query_endswith1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

And and Or Operators
The following sample shows how to retrieve contacts where Address1_City is “Redmond” or “Bellevue” and a CreditLimit that is greater than $200.

 var query_andor1 = from c in svcContext.ContactSet
                    where ((c.Address1_City == "Redmond" ||
                    c.Address1_City == "Bellevue") &&
                    (c.CreditLimit.Value != null &&
                    c.CreditLimit.Value >= 200))
                    select c;

 foreach (var c in query_andor1)
 {
  System.Console.WriteLine(c.LastName + ", " + c.FirstName + " " +
   c.Address1_City + " " + c.CreditLimit.Value);
 }


OrderBy Operator
The following sample shows how to retrieve contacts ordered by CreditLimit in descending order.

 var query_orderby1 = from c in svcContext.ContactSet
                      where !c.CreditLimit.Equals(null)
                      orderby c.CreditLimit descending
                      select new
                      {
                       limit = c.CreditLimit,
                       first = c.FirstName,
                       last = c.LastName
                      };
 foreach (var c in query_orderby1)
 {
  System.Console.WriteLine(c.limit.Value + " " +
   c.last + ", " + c.first);
 }

The following sample shows how to retrieve contacts ordered by LastName in descending order and FirstName in ascending order.

 var query_orderby2 = from c in svcContext.ContactSet
                      orderby c.LastName descending,
                      c.FirstName ascending
                      select new
                      {
                       first = c.FirstName,
                       last = c.LastName
                      };

 foreach (var c in query_orderby2)
 {
  System.Console.WriteLine(c.last + ", " + c.first);
 }

First and Single Operators
The following sample shows how to retrieve only the first contact record returned and retrieve only one contact record that matches the criterion.

using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 Contact firstcontact = svcContext.ContactSet.First();

 Contact singlecontact = svcContext.ContactSet.Single(c => c.ContactId == _contactId1);
 System.Console.WriteLine(firstcontact.LastName + ", " +
  firstcontact.FirstName + " is the first contact");
 System.Console.WriteLine("==========================");
 System.Console.WriteLine(singlecontact.LastName + ", " +
  singlecontact.FirstName + " is the single contact");
}

Retrieving Formatted Values
The following sample shows how to retrieve the label for an optionset option, in this case the value for the current record status.


using (ServiceContext svcContext = new ServiceContext(_serviceProxy))
{
 var list_retrieve1 = from c in svcContext.ContactSet
                      where c.ContactId == _contactId1
                      select new { StatusReason = c.FormattedValues["statuscode"] };
 foreach (var c in list_retrieve1)
 {
  System.Console.WriteLine("Status: " + c.StatusReason);
 }
}

Skip and Take Operators without Paging
The following sample shows how to retrieve just two records after skipping two records where the LastName is not “Parker” using the Skip and Takeoperators.

 var query_skip = (from c in svcContext.ContactSet
                   where c.LastName != "Parker"
                   orderby c.FirstName
                   select new
                       {
                        last = c.LastName,
                        first = c.FirstName
                       }).Skip(2).Take(2);
 foreach (var c in query_skip)
 {
  System.Console.WriteLine(c.first + " " + c.last);
 }

FirstOrDefault and SingleOrDefault Operators
The FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found. The SingleOrDefault operator returns a single, specific element of a sequence, or a default value if that element is not found. The following sample shows how to use these operators.

 Contact firstorcontact = svcContext.ContactSet.FirstOrDefault();

 Contact singleorcontact = svcContext.ContactSet
  .SingleOrDefault(c => c.ContactId == _contactId1);


 System.Console.WriteLine(firstorcontact.FullName +
  " is the first contact");
 System.Console.WriteLine("==========================");
 System.Console.WriteLine(singleorcontact.FullName +
  " is the single contact");

Self Join with a Condition on the Linked Entity
The following sample shows how to retrieve the names of two accounts where one account is the parent account of the other.

 var query_joincond = from a1 in svcContext.AccountSet
                      join a2 in svcContext.AccountSet
                      on a1.ParentAccountId.Id equals a2.AccountId
                      where a2.AccountId == _accountId1
                      select new { Account = a1, Parent = a2 };
 foreach (var a in query_joincond)
 {
  System.Console.WriteLine(a.Account.Name + " " + a.Parent.Name);
 }


Transformation in the Where Clause
The following sample shows how to retrieve a specific contact where the anniversary date is later than January 1, 2010.

 var query_wheretrans = from c in svcContext.ContactSet
                        where c.ContactId == _contactId1 &&
                        c.Anniversary > DateTime.Parse("1/1/2010")
                        select new
                        {
                         c.FirstName,
                         c.LastName
                        };
 foreach (var c in query_wheretrans)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }


Paging Sort
The following sample shows a multi-column sort with an extra condition.

 var query_pagingsort1 = (from c in svcContext.ContactSet
                          where c.LastName != "Parker"
                          orderby c.LastName ascending,
                          c.FirstName descending
                          select new { c.FirstName, c.LastName })
                          .Skip(2).Take(2);
 foreach (var c in query_pagingsort1)
 {
  System.Console.WriteLine(c.FirstName + " " + c.LastName);
 }

The following sample shows a paging sort where the column being sorted is different from the column being retrieved.

 var query_pagingsort2 = (from c in svcContext.ContactSet
                          where c.LastName != "Parker"
                          orderby c.FirstName descending
                          select new { c.FirstName }).Skip(2).Take(2);
 foreach (var c in query_pagingsort2)
 {
  System.Console.WriteLine(c.FirstName);
 }

The following sample shows how to retrieve just the first 10 records.

 var query_pagingsort3 = (from c in svcContext.ContactSet
                          where c.LastName.StartsWith("W")
                          orderby c.MiddleName ascending,
                          c.FirstName descending
                          select new
                          {
                           c.FirstName,
                           c.MiddleName,
                           c.LastName
                          }).Take(10);
 foreach (var c in query_pagingsort3)
 {
  System.Console.WriteLine(c.FirstName + " " +
   c.MiddleName + " " + c.LastName);
 }

Retrieve Related Entity Columns for 1 to N Relationships
The following sample shows how to retrieve columns from related account and contact records.

 var query_retrieve1 = from c in svcContext.ContactSet
                       join a in svcContext.AccountSet
                       on c.ContactId equals a.PrimaryContactId.Id
                       where c.ContactId != _contactId1
                       select new { Contact = c, Account = a };
 foreach (var c in query_retrieve1)
 {
  System.Console.WriteLine("Acct: " + c.Account.Name +
   "\t\t" + "Contact: " + c.Contact.FullName);
 }

Use .Value to Retrieve the Value of an Attribute
The following sample shows usage of Value to access the value of an attribute.

 var query_value = from c in svcContext.ContactSet
                   where c.ContactId != _contactId2
                   select new
                   {
                    ContactId = c.ContactId != null ?
                     c.ContactId.Value : Guid.Empty,
                    NumberOfChildren = c.NumberOfChildren != null ?
                     c.NumberOfChildren.Value : default(int),
                    CreditOnHold = c.CreditOnHold != null ?
                     c.CreditOnHold.Value : default(bool),
                    Anniversary = c.Anniversary != null ?
                     c.Anniversary.Value : default(DateTime)
                   };

 foreach (var c in query_value)
 {
  System.Console.WriteLine(c.ContactId + " " + c.NumberOfChildren +
   " " + c.CreditOnHold + " " + c.Anniversary);
 }

Multiple Projections, New Data Type Casting to Different Types
The following sample shows multiple projections and how to cast values to a different type.

 var query_projections = from c in svcContext.ContactSet
                         where c.ContactId == _contactId1
                         && c.NumberOfChildren != null &&
                         c.Anniversary.Value != null
                         select new
                         {
                          Contact = new Contact {
                           LastName = c.LastName,
                           NumberOfChildren = c.NumberOfChildren
                          },
                          NumberOfChildren = (double)c.NumberOfChildren,
                          Anniversary = c.Anniversary.Value.AddYears(1),
                         };
 foreach (var c in query_projections)
 {
  System.Console.WriteLine(c.Contact.LastName + " " +
   c.NumberOfChildren + " " + c.Anniversary);
 }

GetAttributeValue Method
The following sample shows how to use the GetAttributeValue method.

 var query_getattrib = from c in svcContext.ContactSet
                       where c.GetAttributeValue<Guid>("contactid") != _contactId1
                       select new
                       {
                        ContactId = c.GetAttributeValue<Guid?>("contactid"),
                        NumberOfChildren = c.GetAttributeValue<int?>("numberofchildren"),
                        CreditOnHold = c.GetAttributeValue<bool?>("creditonhold"),
                        Anniversary = c.GetAttributeValue<DateTime?>("anniversary"),
                       };

 foreach (var c in query_getattrib)
 {
  System.Console.WriteLine(c.ContactId + " " + c.NumberOfChildren +
   " " + c.CreditOnHold + " " + c.Anniversary);
 }

Math Methods
The following sample shows how to use various Math methods.

 var query_math = from c in svcContext.ContactSet
                  where c.ContactId != _contactId2
                  && c.Address1_Latitude != null &&
                  c.Address1_Longitude != null
                  select new
                  {
                   Round = Math.Round(c.Address1_Latitude.Value),
                   Floor = Math.Floor(c.Address1_Latitude.Value),
                   Ceiling = Math.Ceiling(c.Address1_Latitude.Value),
                   Abs = Math.Abs(c.Address1_Latitude.Value),
                  };
 foreach (var c in query_math)
 {
  System.Console.WriteLine(c.Round + " " + c.Floor +
   " " + c.Ceiling + " " + c.Abs);
 }

Use Multiple Select and Where Clauses
The following sample shows multiple select and where clauses using a method-based query syntax.

 var query_multiselect = svcContext.IncidentSet
                        .Where(i => i.IncidentId != _incidentId1)
                        .Select(i => i.incident_customer_accounts)
                        .Where(a => a.AccountId != _accountId2)
                        .Select(a => a.account_primary_contact)
                        .OrderBy(c => c.FirstName)
                        .Select(c => c.ContactId);
 foreach (var c in query_multiselect)
 {
  System.Console.WriteLine(c.GetValueOrDefault());
 }

Use SelectMany
The following sample shows how to use the SelectMany Method.

 var query_selectmany = svcContext.ContactSet
                        .Where(c => c.ContactId != _contactId2)
                        .SelectMany(c => c.account_primary_contact)
                        .OrderBy(a => a.Name);
 foreach (var c in query_selectmany)
 {
  System.Console.WriteLine(c.AccountId + " " + c.Name);
 }

String Operations
The following sample shows how to use various String methods.

 var query_string = from c in svcContext.ContactSet
                    where c.ContactId == _contactId2
                    select new
                    {
                     IndexOf = c.FirstName.IndexOf("contact"),
                     Insert = c.FirstName.Insert(1, "Insert"),
                     Remove = c.FirstName.Remove(1, 1),
                     Substring = c.FirstName.Substring(1, 1),
                     ToUpper = c.FirstName.ToUpper(),
                     ToLower = c.FirstName.ToLower(),
                     TrimStart = c.FirstName.TrimStart(),
                     TrimEnd = c.FirstName.TrimEnd(),
                    };

 foreach (var c in query_string)
 {
  System.Console.WriteLine(c.IndexOf + "\n" + c.Insert + "\n" +
   c.Remove + "\n" + c.Substring + "\n"
                           + c.ToUpper + "\n" + c.ToLower +
                           "\n" + c.TrimStart + " " + c.TrimEnd);
 }

Use Two Where Clauses
The following sample shows how to use two Where clauses.

 var query_twowhere = from a in svcContext.AccountSet
                      join c in svcContext.ContactSet
                      on a.PrimaryContactId.Id equals c.ContactId
                      where c.LastName == "Smith" && c.CreditOnHold != null
                      where a.Name == "Contoso Ltd"
                      orderby a.Name
                      select a;
 foreach (var c in query_twowhere)
 {
  System.Console.WriteLine(c.AccountId + " " + c.Name);
 }
}

LoadProperty to Retrieve Related Records
The following sample shows how to LoadProperty to access related records.

Contact benAndrews = svcContext.ContactSet.Where(c => c.FullName == "Ben Andrews").FirstOrDefault();
if (benAndrews != null)
{
 //benAndrews.Contact_Tasks is null until LoadProperty is used.
 svcContext.LoadProperty(benAndrews, "Contact_Tasks");
 Task benAndrewsFirstTask = benAndrews.Contact_Tasks.FirstOrDefault();
 if (benAndrewsFirstTask != null)
 {
  Console.WriteLine("Ben Andrews first task with Subject: '{0}' retrieved.", benAndrewsFirstTask.Subject);
 }



Basic LINQ Query Operations (C#)
Visual Studio 2013
Other Versions

17 out of 19 rated this helpful - Rate this topic
This topic gives a brief introduction to LINQ query expressions and some of the typical kinds of operations that you perform in a query. More detailed information is in the following topics:
LINQ Query Expressions (C# Programming Guide)
Standard Query Operators Overview
Walkthrough: Writing Queries in C# (LINQ)
  Note
If you already are familiar with a query language such as SQL or XQuery, you can skip most of this topic. Read about the "from clause" in the next section to learn about the order of clauses in LINQ query expressions.
Obtaining a Data Source
In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, thefrom clause comes first in order to introduce the data source (customers) and the range variable (cust).
C#
//queryAllCustomers is an IEnumerable<Customer>
var queryAllCustomers = from cust in customers
                        select cust;
The range variable is like the iteration variable in a foreach loop except that no actual iteration occurs in a query expression. When the query is executed, the range variable will serve as a reference to each successive element in customers. Because the compiler can infer the type of cust, you do not have to specify it explicitly. Additional range variables can be introduced by a let clause. For more information, see let clause (C# Reference).
  Note
For non-generic data sources such as ArrayList, the range variable must be explicitly typed. For more information, see How to: Query an ArrayList with LINQ and from clause (C# Reference).

Filtering
Probably the most common query operation is to apply a filter in the form of a Boolean expression. The filter causes the query to return only those elements for which the expression is true. The result is produced by using the where clause. The filter in effect specifies which elements to exclude from the source sequence. In the following example, only those customers who have an address in London are returned.
C#
var queryLondonCustomers = from cust in customers
                           where cust.City == "London"
                           select cust;
You can use the familiar C# logical AND and OR operators to apply as many filter expressions as necessary in the where clause. For example, to return only customers from "London" AND whose name is "Devon" you would write the following code:
C#
where cust.City=="London" && cust.Name == "Devon"
To return customers from London or Paris, you would write the following code:
C#
where cust.City == "London" || cust.City == "Paris"
For more information, see where clause (C# Reference).
Ordering
Often it is convenient to sort the returned data. The orderby clause will cause the elements in the returned sequence to be sorted according to the default comparer for the type being sorted. For example, the following query can be extended to sort the results based on the Name property. Because Name is a string, the default comparer performs an alphabetical sort from A to Z.
C#
var queryLondonCustomers3 =
    from cust in customers
    where cust.City == "London"
    orderby cust.Name ascending
    select cust;
To order the results in reverse order, from Z to A, use the orderby…descending clause.
For more information, see orderby clause (C# Reference).
Grouping
The group clause enables you to group your results based on a key that you specify. For example you could specify that the results should be grouped by the City so that all customers from London or Paris are in individual groups. In this case, cust.City is the key.
C#
// queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>>
  var queryCustomersByCity =
      from cust in customers
      group cust by cust.City;

  // customerGroup is an IGrouping<string, Customer>
  foreach (var customerGroup in queryCustomersByCity)
  {
      Console.WriteLine(customerGroup.Key);
      foreach (Customer customer in customerGroup)
      {
          Console.WriteLine("    {0}", customer.Name);
      }
  }
When you end a query with a group clause, your results take the form of a list of lists. Each element in the list is an object that has a Key member and a list of elements that are grouped under that key. When you iterate over a query that produces a sequence of groups, you must use a nested foreach loop. The outer loop iterates over each group, and the inner loop iterates over each group's members.
If you must refer to the results of a group operation, you can use the into keyword to create an identifier that can be queried further. The following query returns only those groups that contain more than two customers:
C#
// custQuery is an IEnumerable<IGrouping<string, Customer>>
var custQuery =
    from cust in customers
    group cust by cust.City into custGroup
    where custGroup.Count() > 2
    orderby custGroup.Key
    select custGroup;

Joining
Join operations create associations between sequences that are not explicitly modeled in the data sources. For example you can perform a join to find all the customers and distributors who have the same location. In LINQ the join clause always works against object collections instead of database tables directly.
C#
var innerJoinQuery =
    from cust in customers
    join dist in distributors on cust.City equals dist.City
    select new { CustomerName = cust.Name, DistributorName = dist.Name };
In LINQ you do not have to use join as often as you do in SQL because foreign keys in LINQ are represented in the object model as properties that hold a collection of items. For example, a Customer object contains a collection of Order objects. Rather than performing a join, you access the orders by using dot notation:
from order in Customer.Orders...
For more information, see join clause (C# Reference).
Selecting (Projections)
The select clause produces the results of the query and specifies the "shape" or type of each returned element. For example, you can specify whether your results will consist of complete Customer objects, just one member, a subset of members, or some completely different result type based on a computation or new object creation. When theselect clause produces something other than a copy of the source element, the operation is called a projection. The use of projections to transform data is a powerful capability of LINQ query expressions. For more information, see Data Transformations with LINQ (C#) and select clause (C# Reference).


No comments:

Post a Comment