2010-03-17 50 views
3

我試圖找到如下的解決方案(我使用LINQ思考)以下:2個數組的內部連接?

我需要從文件較大列表下拉具有相似的FTP服務器上的特定文件文件名。例如,我們發送訂單文件給某公司進行處理,然後他們返回一個我們可以下載的響應文件。

所以,我可以給他們發送文件「order_123.txt」和「order_456.txt」。經過一段時間後,我需要去查找並下載那些名爲「order_123.resp」和「order_456.resp」的文件的響應。在某些情況下,我可以有多個響應,在這種情況下,他們會創建「order_123-1.resp」和「order_123-2.resp」,並且這些文件不會從服務器中刪除。

我知道這可以通過循環遍歷文件來實現我知道我需要響應然後遍歷服務器上的所有文件,直到找到匹配的文件,但我希望我不必循環服務器上的文件不止一次。

這個例子可能有助於澄清:

我送他們處理他們和FTP服務器包含 「order_222.txt」 和 「order_333.txt」: 「order_111-1.resp」 「order_001。響應」 「order_222-1.resp」 「order_222-2.resp」 「order_333.resp」

我需要下載第3,第4,第5和文件。

謝謝。

回答

0

下面是做這件事:

string[] requests = { "order_222.txt", "order_333.txt" }; 
string[] responses = { 
         "order_111-1.resp", 
         "order_001.resp", 
         "order_222-1.resp", 
         "order_222-2.resp", 
         "order_333.resp" 
        }; 

Regex regex = new Regex(@"(-\d+)?\.resp$"); 
IEnumerable<string> toDownload = 
    responses.Where(x => requests.Contains(regex.Replace(x, ".txt"))); 
foreach (string filename in toDownload) 
    Console.WriteLine(filename); 

輸出:

order_222-1.resp 
order_222-2.resp 
order_333.resp 

它每次使用線性查找請求陣列英寸這可以通過使用散列查找(Dictionary,HashSet等)來改進。

+0

如果你的答覆[]包含字符串[]響應= { 「order_111_1.resp」, 「order_111_1.txt」, 「order_001.resp」, 「order_222_1。 resp「, 」order_222.txt「, 」order_222_2.resp「, 」order_333.resp「, 」order_333.txt「 }; 你只想要他們各自的.resp文件(並注意「_」而不是「 - 」) – scarpacci 2010-03-17 22:10:17

0

試試這個

string[] requests = { 
      "order_222.txt", 
      "order_333.txt" }; 
string[] responses = { 
      "order_222.txt", 
      "order_333.txt", 
      "order_111-1.resp", 
      "order_001.resp", 
      "order_222-1.resp", 
      "order_222-2.resp", 
      "order_333.resp" 
      }; 

var r = from req in requests 
     from res in responses 
     where res.StartsWith(Path.GetFileNameWithoutExtension(req)) 
       && Path.GetExtension(res) == ".resp" 
     select res;