简体   繁体   中英

How to check the property elementAt() has a value and its not null

Sometimes the elements that I am checking against do not exist and the application throws an error.

if(responseSerialNumber.ElementAt(1) == 0)
{
    //Do the following
}  

How can I do deal with this?

There are 2 ways of solving this problem.
First, just check if the array has enough elements before accessing:

if(responseSerialNumber.Length > 2 && responseSerialNumber.ElementAt(1) == 0)
{
    //Do the following
}

The second way is to use ElementAtOrDefault() which returns the appropriate default value based on the type of the array.

var item = responseSerialNumber.ElementAtOrDefault(1);
if (item != default(byte)) { // or use "(item != null)" if item is an reference type
   //Do the following
}

BEWARE: The second solution would work fine if you have an array of non-value types (in this case they can have null as default value). If you have byte array, stick with the first solution.

If responseSerialNumber is an array byte[] (see comments) you can check the array : first for its Length then for the value

if (responseSerialNumber.Length >= 2 && responseSerialNumber[1] == 0) {
  ...
}    

Or (for arbitrary indexAt and valueToTest ):

if (responseSerialNumber.Length >= indexAt + 1 &&
    responseSerialNumber[indexAt] == valueToTest) {
  ...
}

In general case (when responseSerialNumber is IEnumerable<T> ) for given

int indexAt = 1;
valueToTest = 0;

we can Skip indexAt items and check the very next one:

if (responseSerialNumber.Skip(indexAt).Take(1).Any(item => item == valueToTest)) {
  // responseSerialNumber has at least indexAt items
  // indexAt's items is equal to valueToTest
}

Or even

if (responseSerialNumber.Where(index, value) => 
      index == indexAt && value == valueToTest)) {
  ...
}

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