我正在开发一个新的WPF应用程序,我需要将CSV文件中的记录导出到数据库中,如下所示:
A, 22, 23, 12;B, 32, 4, 33;C, 34, 3 ,33;
&#34 ;;"意味着它是一个换行符。 那么如何使用LINQ获取我的记录?我尝试了这段代码,但我无法弄清楚如何换行:
string[] csvlines = File.ReadAllLines(Filname);
var query = from csvline in csvlines
let data = csvline.Split(',')
select new
{
ID = data[0],
FirstNumber = data[1],
SecondNumber = data[2],
ThirdNumber = data[3]
};
我想要的是:
A 22 23 12
B 32 4 33
C 34 3 33
答案 0 :(得分:3)
我认为这就是你要找的东西:
var query = from line in File.ReadLines(filename)
let csvLines = line.Split(';')
from csvLine in csvLines
where !String.IsNullOrWhiteSpace(csvLine)
let data = csvLine.Split(',')
select new
{
ID = data[0],
FirstNumber = data[1],
SecondNumber = data[2],
ThirdNumber = data[3]
};
使用流利的语法:
var query = File.ReadLines(filename)
.SelectMany(line => line.Split(';'))
.Where(csvLine => !String.IsNullOrWhiteSpace(csvLine))
.Select(csvLine => new {data = csvLine.Split(',')})
.Select(s => new
{
ID = s.data[0],
FirstNumber = s.data[1],
SecondNumber = s.data[2],
ThirdNumber = s.data[3]
});
where
用于防止在行末有分号时尝试解析Split
返回的空行。另一种方法是删除where
子句并将其替换为
let data = csvLine.Split(',')
where data.Length >= 4
或者,用流利的语法进行等效更改。
答案 1 :(得分:0)
var query = File.ReadLines(filename)
.Select(csvLine => csvLine.Split(','))
.Select(s => new
{
ID = s[0],
FirstNumber = s[1],
SecondNumber = s[2],
ThirdNumber = s[3]
});