语言集成查询 (LINQ)
LINQ(Language Integrated Query)语言集成查询是一组用于 C# 和 Visual Basic 语言的扩展。它允许编写 C# 或者 Visual Basic 代码以操作内存数据的方式,查询数据库。LINQ 要求数据用实现了 IEnumerable 或 IEnumerable<T> 接口的数据结构进行存储。
linqsyntax.pngLINQ 简单使用
练习数据
class Product
{
public string Name { get; set; }
public int CategoryID { get; set; }
}
class Category
{
public string Name { get; set; }
public int ID { get; set; }
}
// Specify the first data source.
var categories = new List<Category>()
{
new Category(){Name="Beverages", ID=001},
new Category(){ Name="Condiments", ID=002},
new Category(){ Name="Vegetables", ID=003},
new Category() { Name="Grains", ID=004},
new Category() { Name="Fruit", ID=005}
};
// Specify the second data source.
var products = new List<Product>()
{
new Product{Name="Cola", CategoryID=001},
new Product{Name="Tea", CategoryID=001},
new Product{Name="Mustard", CategoryID=002},
new Product{Name="Pickles", CategoryID=002},
new Product{Name="Carrots", CategoryID=003},
new Product{Name="Bok Choy", CategoryID=003},
new Product{Name="Peaches", CategoryID=005},
new Product{Name="Melons", CategoryID=005},
};
选择(投影)
var categoryNames = categories.Select(category => category.Name);
foreach (var categoryName in categoryNames)
{
Console.WriteLine(categoryName);
}
筛选
var categoryQuery = categories.Where(category => category.ID > 002);
foreach (var category in categoryQuery)
{
Console.WriteLine($"categoryName:{category.Name},categoryID:{category.ID}");
}
排序
var categoryOrdering = categories.OrderByDescending(category => category.ID);
foreach (var category in categoryOrdering)
{
Console.WriteLine($"categoryName:{category.Name},categoryID:{category.ID}");
}
分组
var productGrouping = products.GroupBy(product => product.CategoryID);
foreach (IGrouping<int, Product> ProductGroup in productGrouping)
{
Console.WriteLine($"ProductGroupKey:{ProductGroup.Key}");
foreach (var product in ProductGroup)
{
Console.WriteLine($"ProductName:{product.Name},CategoryID:{product.CategoryID}");
}
}
联接
var joinQuery = categories.Join(products, category => category.ID,
prod => prod.CategoryID,
(category, prod) =>
new
{
ProductName = prod.Name,
Category = category.Name
}
);
foreach (var joinData in joinQuery)
{
Console.WriteLine($"ProductName:{joinData.ProductName},Category:{joinData.Category}");
}
强制立即生成 LINQ 查询结果
使用 ToList 或 ToArray 方法生成包含结果的列表或数组。
var productQuery = from product in products.ToList<Product>() where product.CategoryID == 3 select product;
小结
以上大部分是基于 Fluent Syntax 的最简单 LINQ 应用,另一种形式是使用查询操作符,如“筛选”可用下列方式改写:
var categoryQuery2 = from category in categories where category.ID > 002 select category;
最后,如需详细了解 LINQ,请参阅官方文档,Docs /.NET /C# 指南 /编程指南 /编程概念 /LINQ:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/
网友评论