Introduction
LINQ helps you easily find, filter, or sort data inside lists of your own objects, like people or products.
Jump into concepts and practice - no test required
LINQ helps you easily find, filter, or sort data inside lists of your own objects, like people or products.
var result = from item in collection
where condition
select item;collection is your list of custom objects.
condition is how you filter the objects.
var adults = from person in people
where person.Age >= 18
select person;var names = from person in people
select person.Name;var sortedBooks = from book in books
orderby book.Year
select book;This program creates a list of people, then uses LINQ to find all who are 18 or older. It prints their names.
using System; using System.Collections.Generic; using System.Linq; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { List<Person> people = new List<Person> { new Person { Name = "Alice", Age = 30 }, new Person { Name = "Bob", Age = 17 }, new Person { Name = "Charlie", Age = 25 } }; var adults = from person in people where person.Age >= 18 select person.Name; foreach (var name in adults) { Console.WriteLine(name); } } }
You can use LINQ with any list of your own objects.
LINQ queries are easy to read and write, like asking questions about your data.
Remember to include using System.Linq; to use LINQ features.
LINQ lets you filter, sort, and select data from lists of custom objects easily.
You write simple queries that look like questions about your data.
It works well with your own classes and properties.
Person objects using LINQ?p => p.Name.Person { public string Name; public int Age; } and list people with three persons: Alice(30), Bob(25), and Carol(35), what does this LINQ query return?var result = people.Where(p => p.Age > 28).Select(p => p.Name).ToList();
var adults = people.Where(p => p.Age >= 18).Select(p => p.Name);
foreach(var name in adults) Console.WriteLine(name);
Product objects with properties Name (string) and Price (decimal). How do you create a dictionary with product names as keys and prices as values, but only include products costing more than 50 using LINQ?