Cosytyle Cosytyle - 1 year ago 69
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 Source

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>[] 
    // and so on

var count = idGetters
            .Select(x => x())
            .SkipWhile(x => x == 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download