一:基礎知識
1:linq查詢表達式必須以from子句開頭
2:linq查詢表達式必須以select 或者group子句結尾
3:linq查詢表達式能夠包含0個或多個where子句,一個where子句能夠包含1個或多個布爾條件表單時web
看個簡單的例子sql
int[] values = { 0, 1, 2, 3, 4, 5, 6 }; var value = from v in values where v>2 && v<5 select v; foreach (var v in value) { Console.WriteLine(v); }
其中:
from v in values values是數據源,v能夠看做是查詢過程當中的一個枚舉,
where v>2 && v<5 是查詢條件
select v 把符合條件的枚舉依次添加到var value中去。value是一個可枚舉變量
再看個例子函數
static bool CheckNum(int temp) { if (temp > 2 && temp < 5) { return true; } else { return false; } } static void Main(string[] args) { int[] values = { 0, 1, 2, 3, 4, 5, 6 }; var value = from v in values where CheckNum(v) select v; foreach (var v in value) { Console.WriteLine(v); } Console.ReadKey(); }
如上所示:你能夠在查詢表達式中調用其餘函數
第三個例子code
public class UserInfo { public string name { get; set; } public int id { get; set; } public float salary { get; set; } } class Program { static void Main(string[] args) { List<UserInfo> users = new List<UserInfo>(); for(int i = 0;i<10;i++) { users.Add(new UserInfo { name = "username" + i.ToString(), id = i, salary = i * 1000 }); } var valid_salarys = from user in users select user.salary*0.9; foreach (var valid_salary in valid_salarys) { Console.WriteLine(valid_salary); } Console.ReadKey(); } }
1.咱們是用上一篇文章中講到的對象初始化器初始化users集合的
2.linq表達式獲取的是一個int類型的可枚舉集合,
因此咱們知道主要是select子句決定了獲取的數據的類型,甚至能夠在select子句中建立新類型,好比employee的對象。
二:多類from子句查詢orm
List<UserInfo> users1 = new List<UserInfo>(); List<UserInfo> users2 = new List<UserInfo>(); for (int i = 0; i < 10; i++) { users1.Add( new UserInfo { name = "username1" + i.ToString(), id = i, salary = i * 1000 } ); users2.Add( new UserInfo { name = "username1" + i.ToString(), id = i, salary = i * 1000 } ); } var valid_salarys = from user1 in users1 from user2 in users2 where user1.salary > 1000 && user2.id == user1.id select user1.salary * 0.9; foreach (var valid_salary in valid_salarys) { Console.WriteLine(valid_salary); }
1.UserInfo就是上個例子中的UserInfo類
2.from子句能夠檢索無限多個對象
三:多層form子句查詢對象
public class UserInfo { public string name { get; set; } public int id { get; set; } public float salary { get; set; } public List<UserInfo> family { get; set; } } class Program { static void Main(string[] args) { List<UserInfo> users = new List<UserInfo>(); for (int i = 0; i < 10; i++) { users.Add( new UserInfo { name = "username" + i.ToString(), id = i, salary = i * 1000, family = new List<UserInfo> { new UserInfo { name = "username's family" + i.ToString(), id = i, salary = i * 1000-100 } } } ); } var valid_salarys = from user in users from u in user.family where user.salary>1000 && u.salary>900 select user.salary * 0.9; foreach (var valid_salary in valid_salarys) { Console.WriteLine(valid_salary); } Console.ReadKey(); } }
1.UserInfo類內部有一個List<Userinfo>的集合
2.from子句能夠深刻無限多層。get
四:linq屢次查詢string
int[] values = { 0, 3, 4, 6, 8, 1, 2, 5, 7, 9 }; var value = from v in (from v_in in values where v_in % 2 == 0 select v_in) select v; foreach (var v in value) { Console.WriteLine(v); }
是否是很像sql裏的用法呢?呵呵it