0

I have List<String> clr9, which has a known Count of nine.

What I want to know is how to shorthand something that goes on later in the code.

else if(clr9[0].Equals(clr9[1]) && clr9[0].Equals(clr9[2]) && clr9[0].Equals(clr9[3]))

I've already tried this:

else if(clr9[0].Equals(clr9[1].Equals(clr9[2].Equals(clr9[3]))))

but it doesn't seem to work. Is there any way I can avoid the ampersands? Basically just asking if there's a way to find out if all 4 strings are the same without cluttering up that if statement.

3
  • I might need to add that the numbers next to the clrs dictate their capacity. so clr9 would have 9 items in it. I'm only checking if the first 4 are the same. Not the entire list. Commented Mar 29, 2017 at 2:59
  • 1
    crlX.Skip(1).Take(3).All(str => str == clrX[0]) Commented Mar 29, 2017 at 3:01
  • @Chamkey you don't need to check the capacity, distincting will work for any length of list Commented Mar 29, 2017 at 6:36

4 Answers 4

1

Distinct will work, but I think testing equality directly is more expressive of intent:

if(clr9.Skip(1).All(c => c.Equals(clr9[0])))
Sign up to request clarification or add additional context in comments.

2 Comments

I upvoted as I think this is the best solution so far, but I would use c == clr9[0] instead.
For String I tend to use Equals(String). It's more verbose, in this case perhaps more cluttered than the equality operator. But for String I prefer the syntactical affinity with Equals(String, StringComparison) to the prettier ==.
1

You could distinct the list to remove duplicates and check the length.

e.g.

clr9.Distinct().Count() == 1

or, if you want it to be case insensitive

clr9.Distinct(StringComparer.CurrentCultureIgnoreCase).Count() == 1

Comments

0

Well, if you're only checking all the strings inside a single list like for example clr9. What you can do is use LINQ Distinct:

if (clr9.Distinct().Skip(1).Any())
{
  //Do something
}

T

Hope it helps!

Comments

0

I've come across this situation often enough that I've written a simple extension method for it.

public static bool In<T>(this T val, params T[] options)
{
    return options.Contains(val);
}

And then to use it in your code statement

else if (clr9[0].In(clr9.Skip(1).ToArray()))

Edit based on comment by OP, this works just as well:

else if (clr9[0].In(clr9[1], clr9[2], clr9[3]))

Or

else if (clr9[0].In(clr9.Skip(1).Take(3).ToArray())

1 Comment

object?!?!?! Why not make the method generic?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.