C# 在c中读取文本文件并用逗号拆分#

C# 在c中读取文本文件并用逗号拆分#,c#,arrays,C#,Arrays,我有一个文本文件,其格式如下 Number,Name,Age 我想将此文本文件第一列的“Number”读入数组以查找重复项。以下是我在文件中尝试读取的两种方法 string[] account = File.ReadAllLines(path); string readtext = File.ReadAllText(path); 但每次我尝试拆分数组,只得到第一个逗号左边的内容时,我都失败了。你有什么想法吗?谢谢 如果要根据编号重复所有行: var numDuplicates = Fi

我有一个文本文件,其格式如下

Number,Name,Age
我想将此文本文件第一列的“Number”读入数组以查找重复项。以下是我在文件中尝试读取的两种方法

 string[]  account = File.ReadAllLines(path);
 string readtext = File.ReadAllText(path);

但每次我尝试拆分数组,只得到第一个逗号左边的内容时,我都失败了。你有什么想法吗?谢谢

如果要根据
编号重复所有行

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)));

您需要显式拆分数据以访问其各个部分。否则,您的程序将如何确定它由逗号分隔

我想到的最简单的获取号码的方法如下:

var lines = File.ReadAllLines(path);
var firstLine = lines[0];
var fields = firstLine.Split(',');
var number = fields[0]; // Voilla!

您可以进一步将数字解析为int或其他数字类型(如果它确实是一个数字)。另一方面,如果您只是想测试唯一性,这并不是真正必要的。

如果您专门寻找
字符串.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
}
List importedNumbers=新列表();
//将文件读入字符串数组
var fileContents=System.IO.File.ReadAllLines(路径);
//迭代字符串并将其拆分为各自的列
foreach(fileContents中的字符串行)
{
变量字段=line.Split(',');
if(fields.Count()<3)
抛出新异常(“我们每行至少需要3个字段。”);//您真的可以在这里执行其他操作。。。
//您可能希望对int解析更加小心…(使用TryParse)
var number=int.Parse(字段[0]);
变量名称=字段[1];
var age=int.Parse(字段[2]);
//如果我们已导入此号码,请继续下一条记录
if(导入的编号。包含(编号))
continue;//此时您还可以更新现有记录,而不只是跳过。。。
importedNumbers.Add(number);//跟踪我们导入的数字
}