2017-07-16 37 views
0

我有兩個文本文件。等於兩個文本文件的字符串數組

第1文本文件(個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 
+0

您應該使用equals not ==比較字符串,但是您當前的輸出是什麼? –

+0

@Killer Death:似乎'Test1.txt'包含尾部空格;我已經在代碼中添加了'Trim()'來解決這個問題(請參閱我的編輯) –

+0

嗨德米特里。代碼正在工作。非常感謝你。我會更多地瞭解字典。上帝保佑。 – thompogi

回答

0

,以建立關鍵的收藏我建議使用字典 /值對:

{ "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)); 
+0

'代替'$「{l1},''嗨德米特里。非常感謝你的答覆。我已經使用了代碼,但是我得到了與當前輸出相同的結果。 T1,T2,T3,S1,S2,S3 – thompogi

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

嗨阿列克斯。非常感謝你的答覆。我嘗試了代碼,但我得到了意想不到的字符'$'。 – thompogi

+0

@ThomasArriola這是一個字符串插值,c#6功能。你可以用'l1 +',''' –

相關問題