简体   繁体   中英

Can I make this 'if' condition shorter?

I have this condition:

if (pt.left == anything || pt.left == null || pt.left == borders.left || borders.left == anything)

can I make it shorter? I'm thinking about something like this:

if(pt.left == (anything || null || borders.left) || borders.left == anything)

Is there any way to do it?

You could put the elements in an array and use contains.

if((new string[]{anything, null, borders.left}).Contains(pt.left) || borders.left == anything)

or, putting outside the if:

var arr = new string[]{anything, null, borders.left};
if(arr.Contains(pt.left) || borders.left == anything)

or, with an extension method:

public static class MyExtensions
{
    public static bool IsIn<T>(this T obj, params T[] array)
    {
       return array.Contains(obj);
    }
}

Usage:

if(pt.left.IsIn(anything, null, borders.left) || borders.left == anything)

You can clean this up making an extension method:

//I'm assuming you need value equality
public static bool EqualsOneOf<T>(
    this T value,
    T option1,
    T option2,
    params T[] options)
    where T: IEquatable<T>
{
    if (value.Equals(option1))
        return true;

    if (value.Equals(option2))
        return true;

    if (options != null && options.Contains(value))
        return true;

    return false;
}

And now, your expression would be:

if(pt.left.EqualsOneOf(anything, null, borders.left) || borders.left == anything)  

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