简体   繁体   中英

List.Exists returns wrong values

I was using a List to store all the devices retrieved using a third party library. I am using the Exist method to determine whether a device existing inside a list.

bool bDeviceFound = _devicesFound.Exists(delegate(RCDevice device)
    {
        bool retVal = false;
        if (device != null)
        {
            Regex regex = new Regex(@"Floor[\d]+\/mycamera[\d]+");
            if (regex.IsMatch(device.FullName))
                retVal = true;
        }
        return retVal;
    });

The problem is that delegate never returns true or the execution will never reaches to the code inside the delegate. Am I doing anything wrong here? I have verified the code inside the delegate and Regular expression returns true whenever a match is found.

device.FullName assumes the value "Floor1/mycamera1" to IsMatch to return true.

As suggested by LasseV.Karlsen in one of the comment below , I tried moving the delegate method into a seperate private static bool method and put a break point there. but execution never hit there. Thanks

My guess is the issue lies in this line:

if (regex.IsMatch(rc.FullName))

Why are you checking rc.FullName ? Shouldn't you be checking device.FullName instead since device is what's defined in the delegate?

As a side note, you ought to move the Regex definition outside of the Exists call for better performance. Currently it gets recompiled with each iteration of the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM