LINQ

Language-Integrated Query (LINQ)
          The most visible “language-integrated” part of LINQ is the query expression. Query expressions are written in a declarative query syntax introduced in C# 3.0. By using query syntax, you can perform even complex filtering, ordering, and grouping operations on data sources with a minimum of code.
There are three ways in which you can write a LINQ query in C#:
   1.  Use query syntax.
   2.  Use method syntax.
   3.  Use a combination of query syntax and method syntax.
1.   Using a query expression with method syntax
List<int> numbers1 = new List<int>() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int numCount1 =
    (from num in numbers1
     where num < 3 || num > 7
     select num).Count();
2.   It can be written in method syntax as follows:
var numCount = numbers.Where(n => n < 3 || n > 7).Count();
3.   It can be written by using explicit typing, as follows:
int numCount = numbers.Where(n => n < 3 || n > 7).Count();
Examples:
IEnumerable<Customer> customerQuery =
    from cust in customers
    where cust.City == “London”
    select cust;
foreach (Customer customer in customerQuery)
{
    Console.WriteLine(customer.LastName + “, ” + customer.FirstName);
}
OR
Letting the Compiler Handle Generic Type Declarations
var customerQuery2 =
    from cust in customers
    where cust.City == “London”
    select cust;
foreach(var customer in customerQuery2)
{
    Console.WriteLine(customer.LastName + “, ” + customer.FirstName);
}
Example:
class LINQQueryExpressions
{
    static void Main()
    {
        // Specify the data source.
        int[] scores = new int[] { 97, 92, 81, 60 };
        // Define the query expression.
        IEnumerable<int> scoreQuery =
            from score in scores
            where score > 80
            select score;
        // Execute the query.
        foreach (int i in scoreQuery)
        {
            Console.Write(i + ” “);
        }           
    }
}
Populate object collection from multiple sources
1.   Save output into an Object
class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public List<int> ExamScores { get; set; }
}
class PopulateCollection
{
    static void Main()
    {
        // These data files are defined in How to: Join Content from
        // Dissimilar Files (LINQ).
        // Each line of names.csv consists of a last name, a first name, and an
        // ID number, separated by commas. For example, Omelchenko,Svetlana,111
        string[] names = System.IO.File.ReadAllLines(@”../../../names.csv”);
        // Each line of scores.csv consists of an ID number and four test
        // scores, separated by commas. For example, 111, 97, 92, 81, 60
        string[] scores = System.IO.File.ReadAllLines(@”../../../scores.csv”);
        // Merge the data sources using a named type.
        // var could be used instead of an explicit type. Note the dynamic
        // creation of a list of ints for the ExamScores member. We skip
        // the first item in the split string because it is the student ID,
        // not an exam score.
        IEnumerable<Student> queryNamesScores =
            from nameLine in names
            let splitName = nameLine.Split(‘,’)
            from scoreLine in scores
            let splitScoreLine = scoreLine.Split(‘,’)
            where splitName[2] == splitScoreLine[0]
            select new Student()
            {
                FirstName = splitName[0],
                LastName = splitName[1],
                ID = Convert.ToInt32(splitName[2]),
                ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
                              select Convert.ToInt32(scoreAsText)).
                              ToList()
            };
        // Optional. Store the newly created student objects in memory
        // for faster access in future queries. This could be useful with
        // very large data files.
        List<Student> students = queryNamesScores.ToList();
        // Display each student’s name and exam score average.
        foreach (var student in students)
        {
            Console.WriteLine(“The average score of {0} {1} is {2}.”,
                student.FirstName, student.LastName,
                student.ExamScores.Average());
        }
        //Keep console window open in debug mode
        Console.WriteLine(“Press any key to exit.”);
        Console.ReadKey();
    }
}
/* Output:
    The average score of Omelchenko Svetlana is 82.5.
    The average score of O’Donnell Claire is 72.25.
    The average score of Mortensen Sven is 84.5.
    The average score of Garcia Cesar is 88.25.
    The average score of Garcia Debra is 67.
    The average score of Fakhouri Fadi is 92.25.
    The average score of Feng Hanying is 88.
    The average score of Garcia Hugo is 85.75.
    The average score of Tucker Lance is 81.75.
    The average score of Adams Terry is 85.25.
    The average score of Zabokritski Eugene is 83.
    The average score of Tucker Michael is 92.
 */
2.  Save output into an Anonymous  type
// Merge the data sources by using an anonymous type.
// Note the dynamic creation of a list of ints for the
// ExamScores member. We skip 1 because the first string
// in the array is the student ID, not an exam score.
var queryNamesScores2 =
    from nameLine in names
    let splitName = nameLine.Split(‘,’)
    from scoreLine in scores
    let splitScoreLine = scoreLine.Split(‘,’)
    where splitName[2] == splitScoreLine[0]
    select new
    {
        First = splitName[0],
        Last = splitName[1],
        ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
                      select Convert.ToInt32(scoreAsText))
                      .ToList()
    };
// Display each student’s name and exam score average.
foreach (var student in queryNamesScores2)
{
    Console.WriteLine(“The average score of {0} {1} is {2}.”,
        student.First, student.Last, student.ExamScores.Average());
}

Each of the below will produce the same results.
string[] camps = new string[]{“CodeCamp2007″,”CodeCamp2008″,”CodeCamp2009”};
var currentCamp = from camp in camps
   where camp.EndsWith(DateTime.Now.Year.ToString())
   select camp;
string currentCamp2 = camps.Where(c => c.EndsWith( DateTime.Now.Year.ToString())).Single();
string currentCamp3 = camps.Single(c => c.EndsWith( DateTime.Now.Year.ToString()));
string currentCamp4 = camps.Select(c => c).Where(c => c.EndsWith( DateTime.Now.Year.ToString())).Single();
Continue ReadingLINQ