LINQ 实例大全:101个 LINQ 编程示例

需积分: 9 0 下载量 65 浏览量 更新于2024-07-23 收藏 128KB DOC 举报
Linq 实例101 Linq(Language Integrated Query)是一种强大的查询语言,允许开发者使用SQL样式的语法来查询和操作数据。本文将通过101个Linq实例,展示Linq的强大功能和使用场景。 RestrictionOperators 在Linq中,RestrictionOperators是用来限制查询结果的运算符。它可以根据特定的条件筛选出满足条件的数据。下面我们将通过三个实例来展示RestrictionOperators的使用。 Where-Simple1 在第一个实例中,我们使用了Where运算符来筛选出一个整数数组中小于5的数字。 ```csharp public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; Console.WriteLine("Numbers < 5:"); foreach (var x in lowNums) { Console.WriteLine(x); } } ``` 在上面的代码中,我们使用了Where运算符来筛选出numbers数组中小于5的数字,并将结果存储在lowNums变量中。然后,我们使用foreach循环来输出结果。 Where-Simple2 在第二个实例中,我们使用了Where运算符来筛选出一个产品列表中库存数为0的产品。 ```csharp public void Linq2() { List<Product> products = GetProductList(); var soldOutProducts = from p in products where p.UnitsInStock == 0 select p; Console.WriteLine("Sold out products:"); foreach (var product in soldOutProducts) { Console.WriteLine("{0} is sold out!", product.ProductName); } } ``` 在上面的代码中,我们使用了Where运算符来筛选出products列表中库存数为0的产品,并将结果存储在soldOutProducts变量中。然后,我们使用foreach循环来输出结果。 Where-Simple3 在第三个实例中,我们使用了Where运算符来筛选出一个产品列表中库存数大于0且价格大于3.00的产品。 ```csharp public void Linq3() { List<Product> products = GetProductList(); var expensiveInStockProducts = from p in products where p.UnitsInStock > 0 && p.UnitPrice > 3.00M select p; Console.WriteLine("In-stock products that cost more than 3.00:"); foreach (var product in expensiveInStockProducts) { Console.WriteLine("{0} is in stock and costs more than 3.00.", product.ProductName); } } ``` 在上面的代码中,我们使用了Where运算符来筛选出products列表中库存数大于0且价格大于3.00的产品,并将结果存储在expensiveInStockProducts变量中。然后,我们使用foreach循环来输出结果。 通过这三个实例,我们可以看到RestrictionOperators的强大功能,它可以帮助我们快速地筛选出满足特定条件的数据。