2017-05-03 33 views
1

基本上我需要做的是這樣:比較2個文本文件和出口沒有在一號文件中存在線

File no.1: 
1 
2  
4  
5  
51  
21 

File no.2: 
31 
21 
4 

What should be exported: 
1 
2 
5 
51 

基本上只出口不中,第二存在線文本。

我當前的嘗試:

bool exists = false; 
string[] lines1 = File.ReadAllLines("path1"); 
string[] lines2 = File.ReadAllLines("path2"); 

for (int i = 0; i < lines1.Length; i++) 
{ 
    for (int g = 0; g < lines2.Length; g++) 
    { 
     if (lines1[i] == lines2[g]) 
     { 
      exists = true; 
      Console.WriteLine("Exists!"); 
      break; 
     }     
    } 
    if (!exists) 
    { 
     Console.WriteLine(lines1[i]); 
     exists = false; 
    } 
} 
Console.WriteLine("End of file reached"); 
Console.ReadLine(); 

感覺好像是我用一個適當的功能,雖然這是我想出了,感謝您的幫助!

+1

你確定你不是也想5中結果? –

+0

@FrancescoB。哈哈!你是對的,那是我的不好:) – TricksterJoe

回答

4

根據您的預期結果,您可以使用LINQ和Except擴展方法。就像這樣:

string[] result = lines1.Except(lines2).ToArray(); 
+0

哇!那麼,這只是讓我的嘗試很可悲。非常感謝你,祝你有美好的一天:) – TricksterJoe

+0

這個解決方案可以通過用'File.ReadLines'而不是'File.ReadAllLines'來讀取源文件字符串數組來改進。 – Abion47

1

在一般的情況下,如果file2可以包含複製要保留,我建議使用HashSet<string>

HashSet<string> toSkip = new HashSet<string>(File.ReadLines(path1)); 

var toExport = File 
    .ReadLines(path2) 
    .Where(line => !toSkip.Contains(line)); 
//.ToArray(); // <- if you want to materialize the final result 

// Test 
foreach (var item in toExport) 
    Console.WriteLine(item);