等待两个文本文件的字符串数组

时间:2017-07-16 12:07:02

标签: c# text

我有两个文本文件。

第一个文本文件(Test1.txt)的内容如下:

T1
T2 
T3
S1
S2 
S3

第二个文本文件(Test2.txt)具有如下内容:

T2,James
T3,Cindy
S2,John
S3,Martha

所需的输出(Test3.txt)如下:

T1
James
Cindy
S1
John
Martha

我尝试了下面的代码,但似乎没有考虑第二个文本文件。需要你的帮助人员纠正我的代码。非常感谢你的进步。

string line;
string DatabaseFullPath = @"D:\Test1.txt";
string line2;
string DatabaseFullPath2 = @"D:\Test2.txt";

//write to new text file
using (StreamWriter writetext = new StreamWriter(@"D:\Test3.txt"))

//read second text file
using (var file2 = new StreamReader(DatabaseFullPath2))
{
   line2 = file2.ReadLine();
   var ProjectInfo2 = line2.Split(',');

   //read first text file
   using (var file = new StreamReader(DatabaseFullPath))
   {
      //loop on all lines of first text file
      while ((line = file.ReadLine()) != null)
      {
         //compare lines with all the first column of second text file
         if (line == ProjectInfo2[0])
         {
            //put ProjectInfo2[1] on label 1. label 1 as a container
            label1.Text = ProjectInfo2[1];
         }
         else
         {
            //put line on label 1. label 1 as a container
            label1.Text = line.Trim();
         }

         //write all values of label1.Text
         writetext.WriteLine(label1.Text.Trim());
     }
  }
}

当前输出:

T1
T2 
T3
S1
S2
S3

2 个答案:

答案 0 :(得分:0)

如果是小文件,您可以使用此方法:

var file1 = File.ReadAllLines(@"D:\Test1.txt");
var file2 = File.ReadAllLines(@"D:\Test2.txt");

var result = file1.Select(l1 => 
    file2.FirstOrDefault(l2 => l2.StartsWith($"{l1},"))?.Substring(l1.Length + 1) ?? l1);
File.WriteAllLines(@"D:\Test3.txt", result);

答案 1 :(得分:0)

我建议使用 dictionary 来构建键/值对的集合:

   { "T2", "James"}
   { "T3", "Cindy"}
   { "S2", "John"}
   { "S3", "Martha"}

你可以用这种方式实现它:

using System.Linq;
using System.IO;

...

Dictionary<string, string> CodeToName = File
  .ReadLines("Test2.txt")
  .Select(line => line.Split(','))
  .GroupBy(items => items[0].Trim())
  .ToDictionary(chunk => chunk.Key, 
                chunk => string.Join("; ", chunk.Select(item => item[1].Trim())));

有了字典,您可以轻松找到相应的值:

string name = null;

File.WriteAllLines("Test3.txt", File
  .ReadLines("Test1.txt")
  .Select(line => CodeToName.TryGetValue(line.Trim(), out name) 
     ? name 
     : line));

如果是C#7.0+,您可以将后者简化为

File.WriteAllLines("Test3.txt", File
  .ReadLines("Test1.txt")
  .Select(line => CodeToName.TryGetValue(line.Trim(), out var name) // out var syntax
     ? name 
     : line));