我有一个文本文件,其格式如下
Number,Name,Age
我想在此文本文件的第一列读取“数字”到数组中以查找重复项。这是我尝试在文件中阅读的两种方式。
string[] account = File.ReadAllLines(path);
string readtext = File.ReadAllText(path);
但是每当我尝试将数组拆分为刚刚得到第一个逗号左边的什么时,我就失败了。有什么想法吗?谢谢。
答案 0 :(得分:1)
您需要明确拆分数据以访问其各个部分。您的程序如何能够决定用逗号分隔它?
访问我想到的数字的最简单方法是这样的:
var lines = File.ReadAllLines(path);
var firstLine = lines[0];
var fields = firstLine.Split(',');
var number = fields[0]; // Voilla!
您可以通过将数字解析为int或其他数字类型(如果它确实是数字)来进一步发展。另一方面,如果您只是想测试唯一性,那么这不是必需的。
答案 1 :(得分:0)
如果您想要根据Number
:
var numDuplicates = File.ReadLines(path)
.Select(l => l.Trim().Split(','))
.Where(arr => arr.Length >= 3)
.Select(arr => new {
Number = arr[0].Trim(),
Name = arr[1].Trim(),
Age = arr[2].Trim()
})
.GroupBy(x => x.Number)
.Where(g => g.Count() > 1);
foreach(var dupNumGroup in numDuplicates)
Console.WriteLine("Number:{0} Names:{1} Ages:{2}"
, dupNumGroup.Key
, string.Join(",", dupNumGroup.Select(x => x.Name))
, string.Join(",", dupNumGroup.Select(x => x.Age)));
答案 2 :(得分:0)
如果您正在寻找专门针对string.split
解决方案,这是一个非常简单的方法来完成您所寻找的工作:
List<int> importedNumbers = new List<int>();
// Read our file in to an array of strings
var fileContents = System.IO.File.ReadAllLines(path);
// Iterate over the strings and split them in to their respective columns
foreach (string line in fileContents)
{
var fields = line.Split(',');
if (fields.Count() < 3)
throw new Exception("We need at least 3 fields per line."); // You would REALLY do something else here...
// You would probably want to be more careful about your int parsing... (use TryParse)
var number = int.Parse(fields[0]);
var name = fields[1];
var age = int.Parse(fields[2]);
// if we already imported this number, continue on to the next record
if (importedNumbers.Contains(number))
continue; // You might also update the existing record at this point instead of just skipping...
importedNumbers.Add(number); // Keep track of numbers we have imported
}