How to query data using LINQ in C#?
Using LINQ (Language Integrated Query) to query data in C# is very simple. Here is a simple example:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 使用LINQ查询数据
var evenNumbers = numbers.Where(n => n % 2 == 0);
// 输出查询结果
foreach (var num in evenNumbers)
{
Console.WriteLine(num);
}
}
}
In the example above, we first create a list of integers called numbers, and then use the Where method of LINQ to query the even numbers in the list. In the Where method, we use a lambda expression n => n % 2 == 0 to define the query condition, which means a number is even if the result of the modulo operation is 0. Finally, we output the even numbers to the console by iterating through the query results.