Main
1 static void Main(string[] args) 2 { 3 BasicConcept(); 4 5 QuerySyntax(); 6 7 QueryOperations(); 8 Console.ReadLine(); 9 }
1、Query Syntax、Method Syntax
1 private static void BasicConcept() 2 { 3 int[] numbers = { 5, 10, 8, 3, 6, 12 }; 4 //1、Query syntax 5 var numQuery1 = from num in numbers 6 where num % 2 == 0 7 orderby num 8 select num; 9 foreach (var i in numQuery1) 10 { 11 Console.Write(i + " "); 12 } 13 Console.WriteLine(); 14 //2、Method syntax 15 var numQuery2 = numbers.Where(p => p % 2 == 0).OrderBy(p => p); 16 foreach (var i in numQuery2) 17 { 18 Console.Write(i + " "); 19 } 20 }
2、Query Syntax语法
1 private static void QuerySyntax() 2 { 3 //1、Data Source 4 int[] numbers = { 0, 1, 2, 3, 4, 5, 6 }; 5 6 //2、Query creation 7 var numQuery = from num in numbers 8 where num % 2 == 0 9 select num; 10 11 //3、Query execution 12 foreach (var num in numQuery) 13 { 14 Console.Write("{0,1} ", num); 15 } 16 }
3、关键字group by、join、let、into
1 private static void QueryOperations() 2 { 3 List<Customer> custorms = new List<Customer>(); 4 custorms.Add(new Customer() { Name = "Jack", City = "Beijing" }); 5 custorms.Add(new Customer() { Name = "Joy", City = "Beijing" }); 6 custorms.Add(new Customer() { Name = "Tom", City = "Shanghai" }); 7 8 List<Employee> employees = new List<Employee>(); 9 employees.Add(new Employee() { Name = "Jack", ID = 101 }); 10 employees.Add(new Employee() { Name = "Jackson", ID = 102 }); 11 12 var query = from c in custorms 13 group c by c.City into cusGroup 14 where cusGroup.Count() >= 2 15 select new { City = cusGroup.Key, Number = cusGroup.Count() }; 16 17 //foreach (var cg in query) 18 //{ 19 // Console.WriteLine(cg.Key); 20 // foreach (var c in cg) 21 // { 22 // Console.WriteLine(" {0}", c.Name); 23 // } 24 //} 25 26 foreach (var c in query) 27 { 28 Console.WriteLine("{0} Count {1}", c.City, c.Number); 29 } 30 31 var queryJoin = from c in custorms 32 join e in employees on c.Name equals e.Name 33 select new { PersonName = c.Name, PersonID = e.ID, PersonCity = c.City }; 34 35 foreach (var p in queryJoin) 36 { 37 Console.WriteLine("{0} {1} {2}", p.PersonName, p.PersonID, p.PersonCity); 38 } 39 40 string[] strings = { "Hello World", "This is Friday", "Are you happy?" }; 41 var stringQuery = from s in strings 42 let words = s.Split(' ') 43 from word in words 44 let w = word.ToUpper() 45 select w; 46 foreach (var s in stringQuery) 47 { 48 Console.Write(s + " "); 49 } 50 } 51 class Customer 52 { 53 public string Name 54 { 55 get; 56 set; 57 } 58 public string City 59 { 60 get; 61 set; 62 } 63 } 64 65 class Employee 66 { 67 public string Name { get; set; } 68 public int ID { get; set; } 69 }