2

If you have a string of "1,2,3,1,5,7" you can put this in an array or hash table or whatever is deemed best.

How do you determine that all value are the same? In the above example it would fail but if you had "1,1,1" that would be true.

2
  • 3
    Where is the "Please do my homework" tag? Commented Jul 6, 2009 at 13:54
  • I think this question has been asked before... Commented Jul 6, 2009 at 14:10

5 Answers 5

9

This can be done nicely using lambda expressions.

For an array, named arr:

var allSame = Array.TrueForAll(arr, x => x == arr[0]);

For an list (List<T>), named lst:

var allSame = lst.TrueForAll(x => x == lst[0]);

And for an iterable (IEnumerable<T>), named col:

var first = col.First();
var allSame = col.All(x => x == first);

Note that these methods don't handle empty arrays/lists/iterables however. Such support would be trivial to add however.

Sign up to request clarification or add additional context in comments.

3 Comments

@Martin: It isn't clear in the question whether that's a requirement or not. Of course, it would be very simple to support.
Linq is not an option for this project unfortunately
@Jon: First method (for arrays) doesn't require LINQ though. :)
6

Iterate through each value, store the first value in a variable and compare the rest of the array to that variable. The instant one fails, you know all the values are not the same.

Comments

5

How about something like...

string numArray = "1,1,1,1,1";
return numArrray.Split( ',' ).Distinct().Count() <= 1;

1 Comment

Linq is not an option for this project unfortunately
1

I think using List<T>.TrueForAll would be a slick approach.

http://msdn.microsoft.com/en-us/library/kdxe4x4w.aspx

Comments

1

Not as efficient as a simple loop (as it always processes all items even if the result could be determined sooner), but:

if (new HashSet<string>(numbers.Split(',')).Count == 1) ...

Comments

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.