Cosytyle Cosytyle - 25 days ago 9
C# Question

Better Coding Practice Than If-Else

Lets say I have this code.

int count = 0;
int id = GetFirstId();
count = getCountById(id);

if(count == 0){
id = GetSecondId();
count = getCountById(id);
if(count == 0){
id = GetThirdId();
count = getCountById(id);
}
}


Is there a better way to do this. Is something like a LOOP and CASE Statement inside better?

Answer

If you have different method, you can list the methods and then use LINQ to get first non-zero count. It will work if all of your GetXXXId have same signature.

var idGetters = new Func<int>[] 
{
    GetFirstId,
    GetSecondId,
    GetThirdId
    // and so on
};

var count = idGetters
            .Select(x => x())
            .Select(GetCountById)
            .SkipWhile(x => x == 0)
            .FirstOrDefault();