问题描述
我在CSV文件中包含以下几行(更多内容,但此示例很好).
I have the following lines (more, but this sample is fine) in a CSV file.
Date,Open,High,Low,Close,Volume,Adj Close
2012-11-01,77.60,78.12,77.37,78.05,186200,78.05
2012-10-31,76.96,77.75,76.96,77.47,290700,77.47
2012-10-26,77.30,77.62,76.86,77.36,195100,77.36
我需要对数据执行几个不同的功能,每个功能仅需要一行中的某些字段.即功能1将需要每行第二和第三组数据,功能2将需要第四组数据.我将如何使用LINQ(跳过第一行)?
I need to perform several different functions on the data, each only needing certain fields from a row. i.e. function 1 will need the 2nd and 3rd sets of data from each line, function 2 will need the 4th set of data. How would I do that with LINQ (skipping the first line)?
推荐答案
您可以尝试以下操作:-
You can try this:-
var lines = File.ReadAllLines(@"Linq.csv").Select(x => x.Split(','));
//Considering each line contains same no. of elements
int lineLength = lines.First().Count();
var CSV = lines.Skip(1)
.SelectMany(x => x)
.Select((v, i) => new { Value = v, Index = i % lineLength })
.Where(x => x.Index == 2 || x.Index == 3)
.Select(x => x.Value);
foreach (var data in CSV)
{
Console.WriteLine(data);
}
步骤:-
第1步-从CSV文件中读取所有行,并用逗号分隔,这将导致数组操作系统字符串包含每个值.
第2步-跳过第一个数组(包含标头),然后使用SelectMany将列表展平为一个,接下来,您需要为每个(在展平列表中)相似的集合设置索引,我正在使用Select opertaor做的事情,剩下的最后一件事是过滤&选择项目.
Steps:-
Step 1 - Read all lines from CSV file and split them by Comma(,) which will result in an array os strings with every value.
Step 2 - Skip the first array (which is holding the headers), then use SelectMany to flatten the list into one, Next you need to set the index for each set(in the flatten list)similar, which I am doing with Select opertaor, the last thing left is filtering & selecting the item.
这篇关于使用Linq读取CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!