Simon Simon - 4 months ago 42
C# Question

FirstOrDefault function default value

I have array of objects and I would like to find index of some specific object inside this array:

int ix = Array.IndexOf(products, products.Where(item => item != null && item.Id == "xxx").FirstOrDefault());

Item with Id="xxx" doesn't exists, but the ix result is 1.
So, I guess that default for int is 1. How can I know if 1 belongs to first item or default value? It would be nice if I can set default value to -1.

At the end I have done it with findIndex method, but would like to know how to do it with indexOf method.


So you have two parts of one problem. First, you want to find a product:

var product = products.FirstOrDefault(item => item != null && item.Id == "xxx");

And when that product is found, you want to find its index in the products collection:

int index = Array.IndexOf(products, product);

You're halfway there using FirstOrDefault(). If a product with Id "xxx" does not exist, product will be null. So you can check for that and skip IndexOf() for null:

if (product == null)
    return -1;
    return Array.IndexOf(products, product);

The fact that your current code returns 1, means that products[1] is null.