使用LINQ读取分隔符文本文件
有时我们会处理一些带分隔符数据文本文件。例如,使用”,”分隔的数据,如下图:
然后它们存储到文本文件有这样的列:
- First Name
- Last Name
- Job Title
- City
- Country
在我们读取这个文件之前,先建一个实体类:
1: /// <summary>
2: /// Customer entity
3: /// </summary>
4: /// Author Petter Liu http://wintersun.cnblogs.com
5: public class Customer
6: {
7: public string Firstname { get; set; }
8: public string Lastname { get; set; }
9: public string JobTitle { get; set; }
10: public string City { get; set; }
11: public string Country { get; set; }
12: }
接着我们使用LINQ读取整个文件:1: var query = from line in File.ReadAllLines(filePath)
2: let customerRecord = line.Split(,)
3: select new Customer()
4: {
5: Firstname = customerRecord[0],
6: Lastname = customerRecord[1],
7: JobTitle = customerRecord[2],
8: City = customerRecord[3],
9: Country = customerRecord[4]
10: };
11: foreach (var item in query)
12: {
13: Console.WriteLine("{0}, {1}, {2}, {3}, {4}"
14: , item.Firstname, item.Lastname, item.JobTitle, item.City, item.Country);
15: }
要读取可以带条件的记录也可以,我们filter出Country是UK:
1: var query = from c in
2: (from line in File.ReadAllLines(filePath)
3: let customerRecord = line.Split(,)
4: select new Customer()
5: {
6: Firstname = customerRecord[0],
7: Lastname = customerRecord[1],
8: JobTitle = customerRecord[2],
9: City = customerRecord[3],
10: Country = customerRecord[4]
11: })
12: where c.Country == "UK"
13: select c;
另一例子:
1: var query = from c in
补充:软件开发 , C# ,
上一个:C#中控件的缩写大全
下一个:C#操作Word表格的常见操作