有時我們會處理一些帶分隔符數據文本文件。例如,使用”,”分隔的數據,下面介紹下使用linq讀取分隔符文本文件的方法
如下圖: 然後它們存儲到文本文件有這樣的列: 代碼如下: First Name Last Name Job Title City Country 在我們讀取這個文件之前,先建一個實體類: 代碼如下: /// <summary> /// Customer entity /// </summary> public class Customer{ public string Firstname { get; set; } public string Lastname { get; set; } public string JobTitle { get; set; } public string City { get; set; } public string Country { get; set; } } 接著我們使用LINQ讀取整個文件: 代碼如下: var query = from line in File.ReadAllLines(filePath) let customerRecord = line.Split(',') select new Customer() { Firstname = customerRecord[0], Lastname = customerRecord[1], JobTitle = customerRecord[2], City = customerRecord[3], Country = customerRecord[4] }; foreach (var item in query) { Console.WriteLine("{0}, {1}, {2}, {3}, {4}" , item.Firstname, item.Lastname, item.JobTitle, item.City, item.Country); } 要讀取可以帶條件的記錄也可以,我們filter出Country是UK: 代碼如下: var query = from c in (from line in File.ReadAllLines(filePath) let customerRecord = line.Split(',') select new Customer() { Firstname = customerRecord[0], Lastname = customerRecord[1], JobTitle = customerRecord[2], City = customerRecord[3], Country = customerRecord[4] }) where c.Country == "UK" select c; 另一例子: 代碼如下: var query = from c in (from line in File.ReadAllLines(filePath) let customerRecord = line.Split(',') select new Customer() { Firstname = customerRecord[0], Lastname = customerRecord[1], JobTitle = customerRecord[2], City = customerRecord[3], Country = customerRecord[4] }) where c.JobTitle.Contains("Sales") select c;