2

I am trying to check whether a file path is valid using the following code

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

The UniqueRandom method generates non repeating random numbers between 0 to 4. Each number i represents a file name, which may or may not exist. If the file exist, the getCharBitmap method will return a WritableBitmap object, otherwise, it will return null.

I want to integrate a lambda expression to check whether the method returns null or not, then, if it's not null, I want to remember the i value and exit the foreach loop right away.

How to do this efficiently with the least amount of code?

4

1 回答 1

2

Try

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;
}

Or the same without 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
}
于 2013-03-30T05:52:15.273 回答