有時我們會處理一些帶分隔符數據文本文件。例如,使用”,”分隔的數據,如下圖:
然後它們存儲到文本文件有這樣的列:
在我們讀取這個文件之前,先建一個實體類:
1: /// <summary>
2: /// Customer entity
3: /// </summary>
4: /// Author Petter Liu http://wintersun.cnblogs.com
5: public class Customer
6: {
7: public string Firstname { get; set; }
8: public string Lastname { get; set; }
9: public string JobTitle { get; set; }
10: public string City { get; set; }
11: public string Country { get; set; }
12: }
接著我們使用LINQ讀取整個文件:
1: var query = from line in File.ReadAllLines(filePath)
2: let customerRecord = line.Split(,)
3: select new Customer()
4: {
5: Firstname = customerRecord[0],
6: Lastname = customerRecord[1],
7: JobTitle = customerRecord[2],
8: City = customerRecord[3],
9: Country = customerRecord[4]
10: };
11: foreach (var item in query)
12: {
13: Console.WriteLine("{0}, {1}, {2}, {3}, {4}"
14: , item.Firstname, item.Lastname, item.JobTitle, item.City, item.Country);
15: }
要讀取可以帶條件的記錄也可以,我們filter出Country是UK:
1: var query = from c in
2: (from line in File.ReadAllLines(filePath)
3: let customerRecord = line.Split(,)
4: select new Customer()
5: {
6: Firstname = customerRecord[0],
7: Lastname = customerRecord[1],
8: JobTitle = customerRecord[2],
9: City = customerRecord[3],
10: Country = customerRecord[4]
11: })
12: where c.Country == "UK"
13: select c;
另一例子:
1: var query = from c in