Skip to content
Mario Gutierrez edited this page Jan 7, 2017 · 1 revision
  • A C# query language that allows unified data access to various types of data.
  • LINQ (Language Integrated Query) appears similar to SQL.
  • Based on what data is being targeted, people use different phrases:
    • LINQ to Objects (arrays and collections)
    • LINQ to XML
    • LINQ to DataSet (ADO.NET type)
    • LINQ to Entities (ADO.NET Entity Framework [EF])
    • Parallel LINQ (aka PLINQ) (parallel processing of data)
  • Available in .NET 3.5 and up.
  • Must include 'System.Linq' for core LINQ usage (in System.Core.dll).
string[] games = {"Skyrim", "Fallout 4", "League of Legends"};

IEnumerable<string> subset =
  from game in games
  where game.Contains(" ")
  orderby game
  select game;

It's recommended to use implicit typing instead of IEnumerator<T>.

var subset =
  from game in games
  where //...

More query examples:

// Most basic.
var res = from n in numList select n;

// Using many of the operators.
var res = from n in numList where n>0 && n<10 orderby n descending select n;

// Projection: return a subset type. In this case as an anonymous type.
var res = from book in bookList select new {book.Title, book.Author};
  • LINQ queries return various types which all implement IEnumerator<T>.
  • Deferred execution: LINQ results are not evaluated until you actually iterate over the sequence.
  • Immediate execution: You can return a snapshot of the result sequence with extension methods provided by LINQ. Some are: ToArray<T>(), ToDictionary<TSource, TKey>(), and ToList<T>().
  • Other operators are (join, on, equals, into, group, by).
  • There's also aggregation and set extension methods too:
    • Count(), Reverse(), Intersect(otherRes), Union(otherRes), Concat(otherRes), Distinct(), Max(), Min(), Average(), Sum().
  • LINQ queries are shorthand and actually implemented by a bunch of extension methods (i.e., Where(Func<T> fn), Select(Func<T> fn), etc).

Also, if you have a non-generic collection (like ArrayList) you can use OfType<T>() to convert (and filter) it to a generic collection.

ArrayList myList = new ArrayList();
myList.AddRange(new object[] { 4, "g", new Pineapple(), 88 });

// Create List<T> from integers in myList.
List<int> myList2 = myList.OfType<int>();
Clone this wiki locally