2012-05-23 31 views
2

我有兩個文本文件,C:\Test1.txtC:\Test2.txt編輯VB.NET中的一些文件

C:\Test1.txt數據包括由空格(」「)隔開的柱的:

Data Data 
Data Data 
Data Data 

C:\Test2.txt數據包括:

Data 
Data 
Data 

在Test2的第1列的字段是在第1列中的字段測試1。我試圖從Test1添加匹配的字段。因此,例如:

C:\個Test1.txt

Mercedez Silver 
Bentley Black 
Audi Blue 
BMW White 
Honda Gold 

C:\的test2.txt

BMW 
Mercedez 
Bentley 
Audi 
Honda 

後,我已經運行的代碼:

C:\ Test2的。 txt

BMW White 
Mercedez Silver 
Bentley Black 
Audi Blue 
Honda Gold 

回答

3

所以你只是想找到所有在txt2中的汽車也在txt1中,並從txt1覆蓋txt2中的行。然後這應該工作:

Dim l1Infos = From l1 In IO.File.ReadAllLines("C:\Test1.txt") 
       Select New With {.Line = l1, .Tokens = l1.Split(" "c)} 
Dim result = From l1 In l1Infos 
      Join l2 In IO.File.ReadAllLines("C:\Test2.txt") 
      On l1.Tokens(0) Equals l2 
      Select l1.Line 
IO.File.WriteAllLines("C:\Test2.txt", result) 

請注意,它仍然不安全的特殊數據。

+0

嗨,不,它不是功課。對不起,但我如何發佈我到目前爲止編碼?我很掙扎:( – user1413746

+0

蒂姆,這個編碼看起來不錯,難以忽略任何空行,2)如果在另一個文本文件中找不到汽車,那麼將它留空。 – user1413746

+0

@ user1413746:什麼應該很難?如果您至少使用.NET 3.5,則可以複製/粘貼它。正如我已經提到的,如果你的文件包含更多的空格,它還是不安全的。但無論如何它應該給你一個想法。基本上它會用文件1中的匹配行覆蓋文件2中的所有行(根據汽車)。 –

0

所以你在技術方面的任務是這樣的(根據原來的問題和意見):

  • 假設第一個文件是汽車的字典做出的顏色。
  • 假設第二個文件是make的列表。
  • 您需要使用第一個文件找到匹配的結果。
  • 忽略兩個輸入文件中的空行。
  • 如果未找到make,請將空字符串作爲顏色。

這一個老派的解決方案可以分成3個部分:

'read the first file into a dictionary of make to color 
Dim dict As New Dictionary(Of String, String) 
For Each line As String In IO.File.ReadAllLines("C:\Test1.txt") 
    Dim a() As String = line.Split({" "}, StringSplitOptions.RemoveEmptyEntries) 
    If a.Length = 0 Then Continue For 'ignore blank lines 
    Dim key As String = a(0) 
    Dim value As String = a(1) 
    dict.Add(key, value) 
Next 

'find matches for makes listed in the second file and prepare output 
Dim outputLines As New List(Of String) 
For Each key As String In IO.File.ReadAllLines("C:\Test2.txt") 
    If key = String.Empty Then Continue For 'ignore blank lines 
    Dim value As String = Nothing 
    dict.TryGetValue(key, value) 'leave Color blank if not found 
    outputLines.Add(String.Format("{0} {1}", key, value)) 
Next 

'write output 
IO.File.WriteAllLines("C:\Test3.txt", outputLines) 

內置可擴展,上面可以很容易地進一步調整您的需求。請注意,我輸出到另一個文件(#3)。這是爲了保存輸入用於測試目的。如果出現問題,您希望保留輸入,並且您需要快速修復程序&。在確定它按預期工作後,您可以更改代碼以替換文件#2。