What is LINQ in .NET?
Language INtegrated Query or LINQ for short is a new feature of .NET, introduced as part of .NET 3.5. It is a way of querying lists of items that are stored in memory rather than having to retrieve them from the database all the time. It is roughly equivalent to SQL but is adapted for programming languages. Linq statements always begin with from and end in select. For example, if you have twenty options in the database and you know the options are never going to be large, you could retrieve all the options and then when you want an option, you query the list in memory. For the examples, we have two generic lists, Persons and Series and both the source code for these can be found at the bottom of the page.
You will notice that you will need to create a class to help you with some of these code examples below. You will need to customise the classes, it is not simply a case of using one class every time. If there was one class, I think Microsoft would have built it into the .NET framework. In the full code example below, an example helper class is provided.
LINQ Code | SQL Equivalent |
(from p in persons where p.Series == "007" select p).ToList() | Select * from persons where Series = '007'; |
(from p in persons where p.Age < 30 select p).ToList() | Select * from persons where p.Age < 30; |
(from p in persons where p.Name.Contains("Bristow") select p).ToList() | Select * from persons where Name Like '%Bristow%'; |
(from p in persons orderby p.Name select p).ToList() | Select * from persons order by Name; |
(from p in persons select p) | Select * persons |
((from p in persons select p) | Select * persons Intersect select * from Alias |
(from p in persons select p).Union(from p2 in Alias select p2)).ToList() | Select * from persons |
((from p in persons where p.Series == "Alias" select p) | Select * from persons where Series = 'Alias' |
var Items = (from p in persons join s in series on p.Series equals s.SeriesName | Select p.Name as Character, S.Theme as Theme |
Example
To fully appreciate the LINQ examples, I suggest copying the code below and converting into a C# program then running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Series
{
public string SeriesName { get; set; }
public string Theme { get; set; }
public Series(string strSeries, string strTheme)
{ this.SeriesName = strSeries; Theme = strTheme; }
}
class person
{
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Series { get; set; }
public person(string strpersonName, string strGender, int intAge, string strSeries)
{
Name = strpersonName;
Gender = strGender;
Age = intAge;
Series = strSeries;
}
}
class Program
{
static void Main(string[] args)
{
List
List
List
persons.Add(new person("James Bond","M",56,"007"));
persons.Add(new person("Harry Potter", "M", 21,"Harry Potter"));
persons.Add(new person("Lara Croft", "F", 29,"Tomb Raider"));
persons.Add(new person("Simon Templar", "M", 35,"The Saint"));
persons.Add(new person("Ethan Hunt", "M", 55, "Mission Impossible"));
persons.Add(new person("Sydney Bristow","F", 26,"Alias"));
persons.Add(new person("Jack Bristow", "M", 52,"Alias"));
persons.Add(new person("Hermione Granger", "F", 20, "Harry Potter"));
persons.Add(new person("Ron Weasley", "M", 20, "Harry Potter"));
persons.Add(new person("Auric Goldfinger", "M", 51, "007"));
persons.Add(new person("Honey Rider", "F", 26, "007"));
persons.Add(new person("Odd Job", "M", 48, "007"));
persons.Add(new person("Felix Leiter", "M", 45, "007"));
persons.Add(new person("Arvin Sloane", "M", 62, "Alias"));
persons.Add(new person("Bilbo Baggins","M",124,"Lord of the Rings"));
persons.Add(new person("Gandalf","M",87,"Lord of the Rings"));
persons.Add(new person("Han Solo","M",32,"Star Wars"));
persons.Add(new person("Princess Leia","F",21,"Star Wars"));
persons.Add(new person("Yoda","M",900,"Star Wars"));
persons.Add(new person("John Cricthon", "M",35, "Farscape"));
persons.Add(new person("Aeryn Sun","F",28,"Farscape"));
persons.Add(new person("Sikozu","F",28,"Farscape"));
Alias.Add(new person("Sydney Bristow", "F", 26, "Alias"));
Alias.Add(new person("Jack Bristow", "M", 52, "Alias"));
Alias.Add(new person("Marcus Dixon", "M", 51, "Alias"));
List
series.Add(new Series("Alias","Espoinage"));
series.Add(new Series("007", "Espoinage"));
series.Add(new Series("Harry Potter","Fantasy"));
series.Add(new Series("The Saint","Espoinage"));
series.Add(new Series("Lord of the Rings","Fantasy"));
series.Add(new Series("Mission Impossible","Espoinage"));
series.Add(new Series("Farscape","Sci-Fi"));
series.Add(new Series("Star Wars","Sci-Fi"));
DisplayList("List of Characters from 007", (from p in persons where p.Series == "007" select p).ToList());
DisplayList("List of Characters Under 30", (from p in persons where p.Age < 30 select p).ToList());
DisplayList("List of Characters Who are 'Bristows'", (from p in persons where p.Name.Contains("Bristow") select p).ToList());
DisplayList("List of Characters Sorted by Name", (from p in persons orderby p.Name select p).ToList());
DisplayList("List of Characters that are Female", (from p in persons select p)
.Except(from p in persons where p.Gender == "M" select p).ToList());
DisplayList("List of Characters Intersecting",((from p in persons select p)
.Intersect(from p2 in Alias select p2, new PersonComparer())).ToList());
DisplayList("List of Characters from Both Lists", ((from p in persons select p)
.Union(from p2 in Alias select p2)).ToList());
List = ((from p in persons where p.Series == "Alias" select p)
.Concat(from p2 in Alias select p2)).ToList()
.Distinct(new PersonComparer()).ToList();
DisplayList("List of All Unique Characters from Alias in Both Lists",List.ToList() );
var Items = (from p in persons join s in series on p.Series equals s.SeriesName
orderby p.Name
select new { Character = p.Name, Theme = s.Theme }).ToList();
foreach (var Character in Items)
Console.WriteLine(Character.Character + " is a character in a " + Character.Theme + " series");
Console.ReadLine();
}
static void DisplayList( string strTitle, List
{
Console.Write(strTitle + "" + new string('-', strTitle.Length)+"");
foreach (person P in ListPerson)
Console.WriteLine(P.Name);
Console.WriteLine("");
}
}
class PersonComparer : IEqualityComparer
{
// Products are equal if their names and product numbers are equal.
public bool Equals(person x, person y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y))
return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Name == y.Name && x.Name == y.Name;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(person person)
{
//Check whether the object is null
if (Object.ReferenceEquals(person, null))
return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = person.Name == null ? 0 : person.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = person.Name.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
} }
Last Modified : June 2023