欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用linq讀取分隔符文本文件

 更新時間:2014年01月22日 14:54:20   作者:  
有時我們會處理一些帶分隔符數(shù)據(jù)文本文件。例如,使用”,”分隔的數(shù)據(jù),下面介紹下使用linq讀取分隔符文本文件的方法

如下圖:

然后它們存儲到文本文件有這樣的列:

復(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;

相關(guān)文章

最新評論