如下圖:
然后它們存儲到文本文件有這樣的列:
復(fù)制代碼 代碼如下:
First Name
Last Name
Job Title
City
Country
在我們讀取這個文件之前,先建一個實體類:
復(fù)制代碼 代碼如下:
/// 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讀取整個文件:
復(fù)制代碼 代碼如下:
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:
復(fù)制代碼 代碼如下:
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;
另一例子:
復(fù)制代碼 代碼如下:
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;