簡體   English   中英

在文本文件中讀取並在C#中用逗號分割

[英]reading in text file and spliting by comma in c#

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

Number,Name,Age

我想將此文本文件第一列中的“ Number”讀入數組以查找重復項。 這是我嘗試讀取文件的兩種方法。

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

但是每次我嘗試拆分數組以使第一個逗號左邊的內容都失敗時,我就會失敗。 有什么想法嗎? 謝謝。

您需要顯式拆分數據以訪問其各個部分。 否則程序如何確定用逗號分隔?

訪問我想到的數字的最簡單方法是這樣的:

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

您可以通過將數字解析為int或其他數字類型(如果確實是數字)來進一步研究。 另一方面,如果您只想測試唯一性,那么這實際上不是必需的。

如果要根據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)));

如果您正在專門尋找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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM