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

叶子小小的,碧绿碧绿的,花儿小小的,好可爱。紫红色的玫瑰花在风中翩翩起舞,玫瑰花树枝上还有调皮又可爱的小刺,你可要当心哦!你看,那个大仙人球旁围着8个小仙人球,好像一家人聚在一起,多欢快呀!

如下图:

然后它们存储到文本文件有这样的列:


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读取分隔符文本文件到此结束。曾经拥有的不要忘记,已经得到的要珍惜,属于自已的不要放弃。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
asp.net读取模版并写入文本文件

.NET中如何将文本文件的内容存储到DataSet

ASP.NET Core自定义本地化好代码教程之从文本文件读取本地化字符串

将文本文件的内容或者文字保存成图片的方法分享

asp.net 读取文本文件并插入数据库的实现代码