12shadow12 12shadow12 - 18 days ago 8
C# Question

exclude something from foreach loop

Is there a way to exclude something from a foreach loop. I am reading a bunch of registry keys and there is one folder which has no read permissions so it errors out and nullifies the foreach loop.

Answer

Well, if you could check first if you got the permissions to do something

e.g.

 public static bool CanReadKey(this RegistryPermission reg, string key)
    {
        try
        {
            RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Read, key);
            r.Demand();
            return true;
        }
        catch (SecurityException)
        {
            return false;
        }
    }

foreach (var key in keys){
    if(!CanReadKey(registry, key)){ continue; }

    // do stuff ...
}

This might help you, take a look at it.

If you really want to exclude it from the loop, you could take a look at Lambda where you can filter first before running it.

It would look something like this (pseudocode)

foreach(var key in keys.where(x => CanReadKey(registry, x))){
    // do stuff
}
Comments