您好,登錄后才能下訂單哦!
這篇文章主要講解了“如何使用linq讀取分隔符文本文件”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何使用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;
感謝各位的閱讀,以上就是“如何使用linq讀取分隔符文本文件”的內容了,經過本文的學習后,相信大家對如何使用linq讀取分隔符文本文件這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。