使用linq读取分隔符文本文件
使用linq读取分隔符文本文件
发布时间:2017-01-07 来源:查字典编辑
摘要:如下图:然后它们存储到文本文件有这样的列:复制代码代码如下:FirstNameLastNameJobTitleCityCountry在我们读...

如下图:

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

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

复制代码 代码如下:

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;

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新asp.net教程学习
热门asp.net教程学习
编程开发子分类