LINQ è in gran parte utile per l'interrogazione di collezioni (o matrici).
Ad esempio, dati i seguenti dati di esempio:
var classroom = new Classroom
{
new Student { Name = "Alice", Grade = 97, HasSnack = true },
new Student { Name = "Bob", Grade = 82, HasSnack = false },
new Student { Name = "Jimmy", Grade = 71, HasSnack = true },
new Student { Name = "Greg", Grade = 90, HasSnack = false },
new Student { Name = "Joe", Grade = 59, HasSnack = false }
}
Possiamo "interrogare" su questi dati usando la sintassi LINQ. Ad esempio, per recuperare tutti gli studenti che hanno uno spuntino oggi:
var studentsWithSnacks = from s in classroom.Students
where s.HasSnack
select s;
Oppure, per recuperare studenti con un punteggio pari o superiore a 90, e restituire solo i loro nomi, non l'oggetto Student
completo:
var topStudentNames = from s in classroom.Students
where s.Grade >= 90
select s.Name;
La funzione LINQ è composta da due sintassi che svolgono le stesse funzioni, hanno prestazioni quasi identiche, ma sono scritte in modo molto diverso. La sintassi dell'esempio precedente è chiamata sintassi della query . L'esempio seguente, tuttavia, illustra la sintassi del metodo . Gli stessi dati verranno restituiti come nell'esempio sopra, ma il modo in cui la query è scritta è diverso.
var topStudentNames = classroom.Students
.Where(s => s.Grade >= 90)
.Select(s => s.Name);