欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-25 11:19:34
如下图: 然后它们存储到文本文件有这样的列:复制代码 代码如下:first namelast namejob titlecitycountry在我们读取这个文件之前,先建...

如下图:
使用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;