2013-03-30 42 views
2

我試圖檢查文件路徑是否有效使用以下代碼使用lambda表達式來檢查filepath是有效的C#

foreach (int i in UniqueRandom(0, 4)) 
{ 
    var wbImage = getCharBitmap(c, rndFolder, i); 
} 

UniqueRandom方法生成非0之間重複的隨機數到4的每個數字i代表一個文件名,可能存在也可能不存在。如果文件存在,則getCharBitmap方法將返回WritableBitmap對象,否則它將返回空值。

我想集成一個lambda表達式來檢查該方法是否返回null,然後,如果它不爲null,我想記住i值並立即退出foreach循環。

如何以最少量的代碼高效地完成此操作?

回答

2

嘗試

var firstExisting = UniqueRandom(0, 4) 
    .Select(i => new 
     { 
      Bitmap = GetCharBitmap(c, rndFolder, i), 
      Number = i 
     }) 
    .FirstOrDefault(x => x.Bitmap != null); 

if (firstExisting != null) 
{ 
    int j = firstExisting.Number; 
} 

還是一樣沒有LINQ:

private static int FirstExisting() 
{ 
    foreach (int i in UniqueRandom(0, 4)) 
    { 
     var wbImage = GetCharBitmap(c, rndFolder, i); 
     if (wbImage != null) 
     { 
      return i; 
     } 
    } 
    throw new Exception("No existing found"); // or return say -1 
} 
+0

我仍然在學習lambda表達式。無論如何,這兩個建議都非常有幫助。謝謝! – PutraKg