Junior — Middle
Can you show an example of using LINQ to perform queries on a collection?
sobes.tech AI
Answer from AI
LINQ (Language Integrated Query) allows for convenient querying of collections in C#. For example, to select all even numbers from a list and sort them in ascending order, you can write:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 3, 6, 1, 4 };
var evenNumbers = from num in numbers
where num % 2 == 0
orderby num
select num;
foreach (var n in evenNumbers)
{
Console.WriteLine(n);
}
}
}
You can also use the extension method:
var evenNumbers = numbers.Where(n => n % 2 == 0).OrderBy(n => n);