Skip to content

Instantly share code, notes, and snippets.

@codenamejason
Last active August 29, 2015 14:19
Show Gist options
  • Save codenamejason/f076919b522eeac4f186 to your computer and use it in GitHub Desktop.
Save codenamejason/f076919b522eeac4f186 to your computer and use it in GitHub Desktop.
LINQ Class in C#
// 04/19/2015
// Jason Romero | Codenamejason
//
//
class IntroToLINQ
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}
//**************************************************************
// Create a data source from an XML document.
// using System.Xml.Linq;
XElement contacts = XElement.Load(@"c:\myContactList.xml");
//***************************************************************
Agency db = new Agency(@"c:\agency.mdf");
// Query for customers in London.
IQueryable<Customer> custQuery =
from cust in db.Customers
where cust.City == "London"
select cust;
//
//***************************************************************
// Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
//LINQ query variables are typed as IEnumerable<T> or a derived type such as IQueryable<T>.
//
IEnumerable<Customer> customerQuery =
from cust in customers
where cust.City == "London"
select cust;
foreach (Customer customer in customerQuery)
{
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}
//
//If you prefer, you can avoid generic syntax by using the var keyword.
//The var keyword instructs the compiler to infer the type of a query variable
//by looking at the data source specified in the from clause.
//
var customerQuery2 =
from cust in customers
where cust.City == "London"
select cust;
foreach(var customer in customerQuery2)
{
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}
//The var keyword is useful when the type of the variable is obvious or when it is not that important
//to explicitly specify nested generic types such as those that are produced by group queries.
//In general, we recommend that if you use var, realize that it can make your code more difficult for
//others to read.
//
//
//Forcing immediate execution
//Queries that perform aggregation functions over a range of source
//elements must first iterate over those elements.
var evenNumQuery =
from num in numbers
where (num % 2) == 0
select num;
int evenNumCount = evenNumQuery.Count();
//
//
//To force immediate execution of any query and cache its results, you can call
//the ToList<TSource> or ToArray<TSource> methods.
//
List<int> numQuery2 =
(from num in numbers
where (num % 2) == 0
select num).ToList();
//
// or like this:
// numQuery3 is still an int[]
//
var numQuery3 =
(from num in numbers
where (num % 2) == 0
select num).ToArray();
//You can also force execution by putting the foreach loop immediately after the query expression.
//However, by calling ToList or ToArray you also cache all the data in a single collection object.
//
//#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, the from clause comes first in
//order to introduce the data source (customers) and the range variable (cust).
//
//queryAllCustomers is an IEnumerable<Customer>
var queryAllCustomers = from cust in customers
select cust;
//
//
//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.
//
var queryLondonCustomers = from cust in customers
where cust.City == "London"
select cust;
//C# logical AND and OR operators to apply as many filter expressions as necessary in the where clause
where cust.City=="London" && cust.Name == "Devon"
//
where cust.City == "London" || cust.City == "Paris"
//
//
//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.
//
//Ordering:
//
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.
//
//Groupiung:
//
// 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.
//
//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.
var innerJoinQuery =
from cust in customers
join dist in distributors on cust.City equals dist.City
select new { CustomerName = cust.Name, DistributorName = dist.Name };
//
//
from order in Customer.Orders...
//
//
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment