你是否遇到过的这样的情况:读划定的文件(CSV或任何类似格式的文件),然后根据一些条件筛选记录(通过检查某些列的值)。
例如,我们假设data.txt文件包含以下记录
Name,Age,CityPerson
1,30,CityAPerson
2,20,CityBPerson
3,25,CityBPerson
4,30,CityAPerson
5,27,CityA
1,30,CityAPerson
2,20,CityBPerson
3,25,CityBPerson
4,30,CityAPerson
5,27,CityA
如果我们找出CityPerson=CityA,而且age >= 30 的所有记录 ,可以使用LINQ去实现。
1
string
delimiter
=
"
,;
"
;
2 List < string > logs = (File.ReadAllLines( @" C:\Data.txt " )
3 // leave blank lines
4 .Where(line => ! string .IsNullOrEmpty(line))
5 // split line seperated by delimiter
6 .Select(line => line.Split(delimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
7 // compare the third column to find all records from CityA
8 .Where(values => values[ 2 ].Equals( " CityA " , StringComparison.CurrentCultureIgnoreCase))
9 // compare the second column to find all records with age more than or equal to 30
10 .Where(values => int .Parse(values[ 1 ]) >= 30 )
11 // join back the splitted values by underscore
12 .Select(values => string .Join( " _ " , values))
13 // find all unique values
14 .Distinct()
15 .ToList < string > ());
16 // convert to list
2 List < string > logs = (File.ReadAllLines( @" C:\Data.txt " )
3 // leave blank lines
4 .Where(line => ! string .IsNullOrEmpty(line))
5 // split line seperated by delimiter
6 .Select(line => line.Split(delimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
7 // compare the third column to find all records from CityA
8 .Where(values => values[ 2 ].Equals( " CityA " , StringComparison.CurrentCultureIgnoreCase))
9 // compare the second column to find all records with age more than or equal to 30
10 .Where(values => int .Parse(values[ 1 ]) >= 30 )
11 // join back the splitted values by underscore
12 .Select(values => string .Join( " _ " , values))
13 // find all unique values
14 .Distinct()
15 .ToList < string > ());
16 // convert to list
呵呵,是不是很简单明了呢!
本文转自麒麟博客园博客,原文链接:http://www.cnblogs.com/zhuqil/archive/2010/03/22/Using-LINQ-to-read-delimited-text-files.html,如需转载请自行联系原作者