LINQ数据访问技术

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace varQuery
 7 {
 8 class Program
 9 {
10 static void Main(string[] args)
11 {
12 List<Com> lists = new List<Com>
13 {
14 new Com
15 {
16 A = "1",
17 B = "milk",
18 C = "China",
19 D = "100"
20 },
21 new Com
22 {
23 A = "2",
24 B = "banana",
25 C = "Japan",
26 D = "20"
27 },
28 new Com
29 {
30 A = "3",
31 B = "water",
32 C = "USA",
33 D = "10"
34 }
35 };
36 
37 //定义隐型查询表达式
38 var item = from n in lists
39 select new Customer
40 {
41 ID = n.A,
42 Name = n.B,
43 Country = n.C,
44 Price = n.D
45 };
46 
47 //循环访问隐型查询表达式
48 foreach (var i in item)
49 {
50 Console.WriteLine(i);
51 }
52 Console.ReadKey();
53 
54 }
55 }
56 class Com
57 {
58 public String A { get; set; }
59 public String B { get; set; }
60 public String C { get; set; }
61 public String D { get; set; }
62 
63 }
64 
65 
66 class Customer
67 {
68 public String ID { get; set; }
69 public String Name { get; set; }
70 public String Country { get; set; }
71 public String Price { get; set; }
72 public override string ToString()
73 {
74 return "ID = " + ID + ",Name = " + Name + ",Country = " + Country + ",Price = " + Price;
75 }
76 }
77 }

1.使用var创建隐型局部变量

2.Lambda表达式的使用

是一个匿名函数,可以包含表达式和语句,运算符=>,读为goes to,运算符左边为输入参数,右边包含表达式或语句块

 

static void Main(string[] args)
{
//声明一个数组并初始化
string[] strLists = new string[] { "明日科技", "C#编程词典", "C#编程词典珍藏版" };
//使用Lambda表达式查找数组中包含“C#”的字符串
string[] strList = Array.FindAll(strLists, s => (s.IndexOf("C#") >= 0));
//使用foreach语句遍历输出
foreach (string str in strList)
{
Console.WriteLine(str);
}
Console.ReadLine();

 

posted @ 2018-04-20 15:19  东大欧蒂娜  阅读(44)  评论(0)    收藏  举报