Mark Allison Mark Allison - 2 months ago 8
C# Question

Can I rewrite this as a lambda expression?

I have a bit of logic in my code and I'm wondering if there's a better way of re-writing it. I have two user-defined server objects (serverA and serverB) and I want to proceed if both of them are of enum

ServerType
Web
or
Database
.

Current code is clumsy:

if((serverA.ServerType == ServerType.Web || serverA.ServerType == ServerType.Database) && (serverB.ServerType == ServerType.Web || serverB.ServerType == ServerType.Database))
{
// do stuff
}


I'm after an elegant succinct way of writing that.

Answer

I would have a new property in your user-defined server object

public class Server
{
    public ServerType ServerType { get; set; }

    public bool IsDatabaseOrWeb
    {
        get
        {
            return ServerType == ServerType.Web || ServerType == ServerType.Database;
        }            
    }
}

then your function would look like this

if (serverA.IsDatabaseOrWeb && serverB.IsDatabaseOrWeb)
{
   // do stuff
}