如何使用linq语句
LINQ(Language Integrated Query)是一种用于.NET平台的查询语言,可用于查询各种数据源(例如:集合、数据库、XML文档等)。下面是一些使用LINQ语句的示例:
- 查询集合中的数据
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var result = from num in numbers
where num % 2 == 0
select num;
foreach (var num in result)
{
Console.WriteLine(num);
}
输出结果为:
2
4
- 查询XML文档中的数据
XDocument xmlDoc = XDocument.Load("books.xml");
var result = from book in xmlDoc.Descendants("book")
where book.Element("author").Value == "J.K. Rowling"
select book.Element("title").Value;
foreach (var title in result)
{
Console.WriteLine(title);
}
输出结果为:
Harry Potter and the Philosopher's Stone
Harry Potter and the Chamber of Secrets
Harry Potter and the Prisoner of Azkaban
Harry Potter and the Goblet of Fire
Harry Potter and the Order of Phoenix
Harry Potter and the Half Blood Prince
Harry Potter and the Deathly Hallows
- 查询数据库中的数据
using (var context = new MyDatabaseContext())
{
var result = from customer in context.Customers
where customer.City == "London"
select customer;
foreach (var customer in result)
{
Console.WriteLine(customer.Name);
}
}
输出结果为:
John Smith
Emily Jones
原文地址: https://www.cveoy.top/t/topic/bfJa 著作权归作者所有。请勿转载和采集!