12shadow12 12shadow12 - 10 months ago 89
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 Source

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


 public static bool CanReadKey(this RegistryPermission reg, string key)
            RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Read, key);
            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