Linq:从List列表中查询数据(Where查询)
获取List<Customer> customerList的函数见:http://www.cnblogs.com/yf2011/p/3369927.html
输出List中Berlin城市的Customer信息和该Customer订单
1 public void GetCustomerOrderByCity() 2 { 3 List<Customer> customers = GetList(); 4 5 var waCustomers = 6 from cust in customers 7 where cust.City== "Berlin" 8 select cust; 9 10 foreach (var customer in waCustomers) 11 { 12 Console.WriteLine("Customer {0}: {1}", customer.CustomerID, customer.CompanyName); 13 foreach (var order in customer.Orders) 14 { 15 Console.WriteLine(" Order {0}: {1}", order.OrderID, order.OrderDate); 16 } 17 } 18 }
多条件查询
public void GetCustomerOrderByCId() { List<Customer> customers = GetList(); var waCustomers = from cust in customers where cust.CId>1&&cust.CId<5 select cust; foreach (var customer in waCustomers) { Console.WriteLine("Customer {0}: {1}", customer.CustomerID, customer.CompanyName); foreach (var order in customer.Orders) { Console.WriteLine(" Order {0}: {1}", order.OrderID, order.OrderDate); } } }
[Description("查询值的长度比索引小的项.")] public void GetStrInList() { string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; var shortDigits = digits.Where((digit, index) => digit.Length < index); foreach (var d in shortDigits) { Console.WriteLine(d); } Console.ReadLine(); }
在上述示例中 five长度为4索引为5,six长度为3索引为6,seven长度为5索引为7,eight长度为5索引为8,nine长度为4索引为9.输出结果为:
five
six
seven
eight
nine
内容源自:http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b