1.select 查詢且合併欄位
var result =
from mySet in myList
select "ID:"+mySet.StudentId + "," +"Name:"+mySet.StudentName;
注意的地方:
- 一次傳回 StudentID 和 StudentName 欄位合併的字串。
2.傳回匿名型別的LINQ查詢
此種查詢方法比上面方法更為靈活,它是一次傳回一個資料子集。
var result =
from mySet in myList
select new
{
Name = mySet.StudentId + "," + mySet.StudentName,
myAddress = mySet.Address
};
注意的地方:
- 1.result 會收到{ Name = 1,Manish, myAddress = Hyderabad }這樣的資料集。
- 2.查詢回傳給 result 其實是 IEnumerable,其型別為一種新型別:包含屬性Name和myAddress。
3.使用 WHERE 篩選資料
var result =
from mySet in myList
where mySet.Address == "Hyderabad"
select new { mySet.StudentId, mySet.StudentName };
注意的地方:
- 1.首先會先執行where子句,再對得到的可列舉(Enumerable)集合執行Select子句,
- 2.其回傳結果為一個包含StudentId及StudentName之匿名型別。
4.使用 WHERE 篩選資料+篩選學生姓名開頭為"M"
var result =
from mySet in myList
where mySet.StudentName.StartsWith("M")
select mySet.StudentName;
注意的地方:
- StartsWith
5.對資料排序-OrderBy,依照ID遞減排序找出學生姓名
var result =
from mySet in myList
orderby mySet.StudentId descending
select mySet.StudentName;
注意的地方:
- descending
6.對資料群組-Group by,依照電話分群組
var result =
from mySet in myList
group mySet by mySet.MobileNo;
注意的地方:
- group mySet by mySet.MobileNo
- 對mySet資料集依照MobileNo做Group。
7.Group by分兩群組,此查詢會把MobileNo和Address相同放同一組
var result =
from mySet in myList
group mySet by new { mySet.MobileNo, mySet.Address };
注意的地方:
- group mySet by new { mySet.MobileNo, mySet.Address };
- 所以ID:1,Name:Manish , ID:2,Name:Venkat 放入同一組
8.Join:可以將兩個不同類別組合再一起(這裡只是為了方便才把Student2弄得這麼像Student類別)
var result =
from mySet in myList
join mySet2 in myList2
on mySet.StudentId equals mySet2.StudentId2
select new
{
mySet.StudentId,
mySet.StudentName,
mySet2.StudentId2,
mySet2.StudentName2
};
注意的地方:
- mySet.StudentId equals mySet2.StudentId2
完整程式碼:
https://drive.google.com/open?id=
0B1K8K3aq2Hqbd203YjQ3UXFFNDQ&authuser=0