您好,登錄后才能下訂單哦!
這篇文章主要講解了“如何使用linq讀取分隔符文本文件”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“如何使用linq讀取分隔符文本文件”吧!
如下圖:
然后它們存儲到文本文件有這樣的列:
復(fù)制代碼 代碼如下:
First Name
Last Name
Job Title
City
Country
在我們讀取這個文件之前,先建一個實(shí)體類:
復(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;
感謝各位的閱讀,以上就是“如何使用linq讀取分隔符文本文件”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對如何使用linq讀取分隔符文本文件這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。