LINQ Primer

I recently did a primer on LINQ for my colleagues at work and I wanted to put my notes in a place where I could get quick access to them … I then remembered that I have a blog for that exact purpose. My notes were designed to cover the basics of LINQ and even more importantly I wanted to cover all the significant changes that made a language integrated query possible in the type safe .NET environment. During the presentation I opted to avoid Power point completely and stick to code samples we could all hack into, and here they are:

1  - ANOTMY OF A Basic Query
string[] ourteam = { "Larry", "Don", "Grishma", "Alex", "Navya", "Ganesh", 
                      "Melvin", "Mark", "Jeff" };

IEnumerable<string> query = from s in ourteam
                            where s.Length == 4
                            orderby s
                            select s;
2a - Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. See my previous post for details.

2b - Lambda Expressions

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. “=>” is the lambda operator, which reads as "goes to".

Func<int, int> f = n => n * 5;
int val = f(5);
Console.WriteLine(val); //Displays 25
2c – Predicates

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.

s => s.Length == 4
2d - Lambda Expressions in practice
string[] ourteam = { "Larry", "Don", "Grishma", "Alex", "Navya", "Ganesh", 
                      "Melvin", "Mark", "Jeff" };

Func<string, bool> filter = s => s.Length == 4;
Func<string, string> extract = s => s;
Func<string, string> project = s => s.ToUpper();

IEnumerable<string> query = ourteam.Where(filter)
    .OrderBy(extract)
    .Select(project);
3 - What IN the var...

An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

var a = “string”; //gives a string
var b = 45; // gives an int
4a - More Query Syntax
string[] ourteam = { "Larry", "Don", "Grishma", "Alex", "Navya", "Ganesh", 
                      "Melvin", "Mark", "Jeff" };
IEnumerable<string> query = ourteam.OrderBy(s => s).ThenBy(s => s.Length);
4b - Query Syntax GROUP BY
string[] ourteam = { "Larry", "Don", "Grishma", "Alex", "Navya", "Ganesh", "Melvin", "Mark", "Jeff" };

var myteamgroup = ourteam.GroupBy(s => s.Length);
foreach (IGrouping<int, string> grouplength in myteamgroup)
{
    Console.WriteLine(String.Format("String Length: {0}: ", grouplength.Key));
    foreach (string names in grouplength)
    {
        Console.WriteLine(String.Format("String Length: {0}: ", names));
    }
}
4c - Query Syntax AGGREGATE
string[] ourteam = { "Larry", "Don", "Grishma", "Alex", "Navya", "Ganesh", "Melvin", "Mark", "Jeff" };
int val = ourteam.Sum(s => s.Length);
Console.WriteLine(val); //total length of all strings
5 - JOIN
class ScoreCard { public int Key; public int Score; }
class Member { public int Key; public string Name; }

class Program
{
    static void Main(string[] args)
    {
        var teamscore = new List<ScoreCard>()
        {
            new ScoreCard {Key = 0, Score = 3 },
            new ScoreCard {Key = 1, Score = 12 },
            new ScoreCard {Key = 2, Score = 67 },
            new ScoreCard {Key = 3, Score = 67 },
            new ScoreCard {Key = 4, Score = 82 },
            new ScoreCard {Key = 5, Score = 100 },
        };

        var ourteam = new List<Member>()
        {
            new Member {Key = 0, Name = "Larry" },
            new Member {Key = 1, Name = "Don" },
            new Member {Key = 2, Name = "Grishma" },
            new Member {Key = 3, Name = "Alex" },
            new Member {Key = 4, Name = "Navya" },
            new Member {Key = 5, Name = "Melvin" },
            new Member {Key = 6, Name = "Mark" },
            new Member {Key = 7, Name = "Jeff" },
        };

        var myteamjoin = from ts in teamscore
                         join ot in ourteam on ts.Key equals ot.Key
                         select new { ot.Name, ts.Score };

        foreach (var mem in myteamjoin)
        {
            Console.WriteLine("Name: {0}, Score {1}", mem.Name, mem.Score);
        }
    }
}


Comment Section

Comments are closed.