2010-06-08 41 views
2

我已經寫代表文件附件到一個列表中(C#3.0)更好的辦法

List<Attachment> lstAttachment = new List<Attachment>(); 

      //Check if any error file is present in which case it needs to be send 
      if (new FileInfo(Path.Combine(errorFolder, errorFileName)).Exists) 
      { 
       Attachment unprocessedFile = new Attachment(Path.Combine(errorFolder, errorFileName)); 
       lstAttachment.Add(unprocessedFile); 
      } 
      //Check if any processed file is present in which case it needs to be send 
      if (new FileInfo(Path.Combine(outputFolder, outputFileName)).Exists) 
      { 
       Attachment processedFile = new Attachment(Path.Combine(outputFolder, outputFileName)); 
       lstAttachment.Add(processedFile); 
      } 

做工精細,並給出預期的輸出。

基本上我根據文件是否存在將文件附加到列表中。

我正在尋找比我寫的任何其他優雅的解決方案。

原因:想學習不同的表示同一個程序的方法。

我正在使用C#3.0

謝謝。

+0

我真的很喜歡LINQ的表現力和優雅;以我的答案爲例。 :) – tzaman 2010-06-08 08:21:13

回答

0

它看起來更好嗎?

... 

var lstAttachment = new List<Attachment>(); 
string errorPath = Path.Combine(errorFolder, errorFileName); 
string outputPath = Path.Combine(outputFolder, outputFileName); 

AddAttachmentToCollection(lstAttachment, errorPath); 
AddAttachmentToCollection(lstAttachment, outputPath); 

... 

public static void AddAttachmentToCollection(ICollection<Attachment> collection, string filePath) 
{ 
    if (File.Exists(filePath)) 
    { 
     var attachment = new Attachment(filePath); 
     collection.Add(attachment); 
    } 
} 
0

有點LINQ怎麼樣?

var filenames = new List<string>() 
{ 
    Path.Combine(errorFolder, errorFilename), 
    Path.Combine(outputFolder, outputFilename) 
}; 
var attachments = filenames.Where(f => File.Exists(f)) 
          .Select(f => new Attachment(f)); 
相關問題