What is LINQ and how do I use it?
Short answer
LINQ adds query methods to any IEnumerable<T>. Where, Select, OrderBy, First, Any and Sum cover most day-to-day use.
using System.Linq;
var videos = new List<Video> { /* … */ };
var popular = videos
.Where(v => v.Views > 200)
.OrderByDescending(v => v.Views)
.Select(v => v.Title)
.ToList();#The core methods
videos.Where(v => v.Views > 200); // filter
videos.Select(v => v.Title); // transform
videos.OrderBy(v => v.Title); // sort
videos.First(v => v.Views > 500); // throws if none
videos.FirstOrDefault(v => …); // null if none
videos.Any(v => v.Views > 500); // bool
videos.All(v => v.Views > 0); // bool
videos.Count(v => v.Views > 200); // int
videos.Sum(v => v.Views);
videos.GroupBy(v => v.Track);
videos.Distinct();
videos.Take(5); videos.Skip(10);#Deferred execution
A LINQ query does not run when you write it. It runs when you enumerate it:
var query = videos.Where(v => v.Views > 200); // nothing has happened yet
videos.Add(new Video { Views = 999 });
var result = query.ToList(); // NOW it runs — includes the new oneThis surprises people the first time. Call .ToList() or .ToArray() to force it immediately.
#Query syntax exists too
var popular = from v in videos
where v.Views > 200
orderby v.Views descending
select v.Title;Identical result. Method syntax is more common and handles everything; query syntax reads better for complex joins and group by.
#First vs Single
.First() // first match, throws if none
.FirstOrDefault() // first match, default if none
.Single() // throws unless there is EXACTLY one
.SingleOrDefault() // throws if more than oneUse Single when more than one match indicates a bug — a lookup by primary key, for instance. The exception is the point.