使用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)文章
ASP.NET性能優(yōu)化之讓瀏覽器緩存動態(tài)網(wǎng)頁的方法
上一篇《ASP.NET性能優(yōu)化之構(gòu)建自定義文件緩存》我們通過OutputCache,讓請求去訪問服務(wù)器asp.net的輸出緩存,我們擴展了OutputCacheProvider,這相當(dāng)于是訪問服務(wù)器上的靜態(tài)資源。2011-09-09ASP.NET Core中修改配置文件后自動加載新配置的方法詳解
這篇文章主要給大家介紹了關(guān)于ASP.NET Core中修改配置文件后自動加載新配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用ASP.NET Core具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08ASP.NET Core MVC如何實現(xiàn)運行時動態(tài)定義Controller類型
這篇文章主要介紹了ASP.NET Core MVC如何實現(xiàn)運行時動態(tài)定義Controller類型,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06自動類型安全的REST.NET標(biāo)準(zhǔn)庫refit
這篇文章介紹了自動類型安全的REST.NET標(biāo)準(zhǔn)庫refit,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04gridview中實現(xiàn)radiobutton的單選示例
radiobutton可以單選,于是想讓gridview也可以實現(xiàn),具體的思路及代碼如下,感興趣的朋友可以參考下2013-08-08