我想从CSV文件创建一个数组.
这很简单,你可以想象,CSV文件只有一行和这些值:
Device, SignalStrength, Location, Time, Age.
Run Code Online (Sandbox Code Playgroud)
我想把这些值放到一维数组中.
我已经尝试了一些例子,但它们都比需要的更复杂.
Ram*_*esh 64
您可以尝试下面的LINQ代码段.
string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv");
var query = from line in allLines
let data = line.Split(',')
select new
{
Device = data[0],
SignalStrength = data[1],
Location = data[2],
Time = data[3],
Age = Convert.ToInt16(data[4])
};
Run Code Online (Sandbox Code Playgroud)
更新:在一段时间内,事情发生了变化.截至目前,我更愿意使用这个库http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx
And*_*are 51
如果只有一行,那么做这样的事情:
using System;
using System.IO;
class Program
{
static void Main()
{
String[] values = File.ReadAllText(@"d:\test.csv").Split(',');
}
}
Run Code Online (Sandbox Code Playgroud)
这是我做的一个简单的功能.它接受字符串CSV行并返回字段数组:
它适用于Excel生成的CSV文件以及许多其他变体.
public static string[] ParseCsvRow(string r)
{
string[] c;
string t;
List<string> resp = new List<string>();
bool cont = false;
string cs = "";
c = r.Split(new char[] { ',' }, StringSplitOptions.None);
foreach (string y in c)
{
string x = y;
if (cont)
{
// End of field
if (x.EndsWith("\""))
{
cs += "," + x.Substring(0, x.Length - 1);
resp.Add(cs);
cs = "";
cont = false;
continue;
}
else
{
// Field still not ended
cs += "," + x;
continue;
}
}
// Fully encapsulated with no comma within
if (x.StartsWith("\"") && x.EndsWith("\""))
{
if ((x.EndsWith("\"\"") && !x.EndsWith("\"\"\"")) && x != "\"\"")
{
cont = true;
cs = x;
continue;
}
resp.Add(x.Substring(1, x.Length - 2));
continue;
}
// Start of encapsulation but comma has split it into at least next field
if (x.StartsWith("\"") && !x.EndsWith("\""))
{
cont = true;
cs += x.Substring(1);
continue;
}
// Non encapsulated complete field
resp.Add(x);
}
return resp.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
184486 次 |
| 最近记录: |