关于在无序列表中,找到所需数据的五种写法
class Program
{
class Product
{
public string name;
public int price;
public override string ToString()
{
return name;
}
}
static void Main(string[] args)
{
List<Product> products = new List<Product>()
{
new Product(){name = "A", price = 5},
new Product(){name = "B", price = 10},
new Product(){name = "C", price = 15},
};
// 例子1
foreach(var product in products)
{
if(product.price >= 10)
{
Console.WriteLine(product);
}
}
// 例子2
Predicate<Product> predicate = delegate (Product p) { return p.price >= 10; };
List<Product> matches = products.FindAll(predicate);
Action<Product> print = Console.WriteLine;
matches.ForEach(print);
// 例子3
products.FindAll((p) => p.price >= 10).ForEach(Console.WriteLine);
// 例子4
foreach(Product product in products.Where(p => p.price >= 10))
{
Console.WriteLine(product);
}
// 例子5 LINQ语法
var filiered = from Product p in products
where p.price >= 10
select p;
foreach(Product product in filiered)
{
Console.WriteLine(product);
}
}
}
标签:10,product,Console,有感,C#,price,Product,---,products
From: https://www.cnblogs.com/chenxiayun/p/18293984