157

If all the items in a list have the same value, then I need to use that value, otherwise I need to use an “otherValue”. I can’t think of a simple and clear way of doing this. When the list is empty it should return the "other" value.

See also Neat way to write loop that has special logic for the first item in a collection.

1

9 Answers 9

200
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue; 

Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.

To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:

if(yyy == null || !yyy.Any()) return otherValue;
5
  • 1
    +1, would using .Any allow for the enumeration to quit early in cases where there are different values?
    – Jeff Ogata
    Dec 8, 2010 at 18:01
  • 14
    @adrift: All will terminate as soon as it hits an element x of the sequence for which x.Value != val. Similarly, Any(x => x.Value != val) would terminate as soon as it hits an element x of the sequence for which x.Value != val. That is, both All and Any exhibit "short-circuiting" analogous to && and || (which is effectively what All and Any are).
    – jason
    Dec 8, 2010 at 18:06
  • @Jason: exactly. All(condition) is effectively !Any(!condition), and the evaluation of either will terminate as soon as the answer is known.
    – KeithS
    Dec 8, 2010 at 18:10
  • 7
    Microoptimisation: return yyy.Skip(1).All(x=>x.Value == val) ? val : otherValue;
    – Caltor
    Dec 13, 2018 at 13:20
  • @Caltor No micro-optimization at all given that Skip is likely to allocate. Apr 17 at 15:12
131

Good quick test for all equal:

collection.Distinct().Count() == 1
7
  • 3
    +1 much cleaner than KeithS' solution IMO. You might want to use collection.Distinct().Count() <= 1 if you want to allow empty collections.
    – 3dGrabber
    Dec 30, 2013 at 12:44
  • 6
    Be careful, .Distinct() does not always work as expected - especially when you work with objects, see this question. In that cases, you need to implement the IEquatable interface.
    – Matt
    May 14, 2014 at 14:46
  • 21
    Cleaner, yes, but less performant in the average case; Distinct() is guaranteed to traverse every single element in the collection once, and in the worst case of every element being different, Count() will traverse the full list twice. Distinct() also creates a HashSet so its behavior can be linear and not NlogN or worse, and that will inflate memory usage. All() makes one full pass in the worst case of all elements being equal, and doesn't create any new collections.
    – KeithS
    Aug 26, 2014 at 21:11
  • 2
    @KeithS As I hope you realize by now, Distinct won't traverse the collection at all, and Count will do one traversal via Distinct's iterator.
    – NetMage
    Dec 9, 2019 at 22:51
  • 3
    One could use an equality comparer in Distinct to use with specific classes. Alternatively, in the manner I have opted to use this answer, with Select to first map a targeted property, e.g.: collection.Select(x => x.Property).Distinct().Count() == 1
    – PJRobot
    Nov 17, 2020 at 20:21
24

Though you certainly can build such a device out of existing sequence operators, I would in this case be inclined to write this one up as a custom sequence operator. Something like:

// Returns "other" if the list is empty.
// Returns "other" if the list is non-empty and there are two different elements.
// Returns the element of the list if it is non-empty and all elements are the same.
public static int Unanimous(this IEnumerable<int> sequence, int other)
{
    int? first = null;
    foreach(var item in sequence)
    {
        if (first == null)
            first = item;
        else if (first.Value != item)
            return other;
    }
    return first ?? other;
}

That's pretty clear, short, covers all the cases, and does not unnecessarily create extra iterations of the sequence.

Making this into a generic method that works on IEnumerable<T> is left as an exercise. :-)

2
  • Say, for example, you have a sequence of nullables and the extracted value is also a nullable. In which case, the sequence could be empty or every item in the sequence could have a null in the extracted value. Coalescing, in this case, would return the other when the null was actually the (presumably) correct response. Say the function was T Unanimous<U, T>(this IEnumerable<U> sequence, T other) or some such signature, that complicates it a bit. Dec 8, 2010 at 18:38
  • @Anthony: Indeed, there are many complications here, but they are pretty easily worked around. I'm using a nullable int as a convenience so that I don't have to declare a "I've seen the first item already" flag. You could easily just declare the flag. Also I'm using "int" instead of T because I know that you can always compare two ints for equality, which is not the case for two Ts. This is more of a sketch of a solution than a fully functional generic solution. Dec 8, 2010 at 18:41
16
return collection.All(i => i == collection.First())) 
    ? collection.First() : otherValue;.

Or if you're worried about executing First() for each element (which could be a valid performance concern):

var first = collection.First();
return collection.All(i => i == first) ? first : otherValue;
5
  • @KeithS - Which is why I added the second part of my answer. On small collections, calling First() is trivial. On large collections, that might start to be an issue. Dec 8, 2010 at 17:42
  • 1
    "On small collections, calling First() is trivial." - That depends on the source of the collection. For a list or array of simple objects, you're absolutely right. But, some enumerables are not finite memory-cached sets of primitives. A collection of delegates, or an enumerator that yields through an algorithmic series calculation (e.g. Fibonacci), would get very expensive to evaluate First() on every time.
    – KeithS
    Dec 8, 2010 at 17:57
  • 6
    Or worse, if the query is a database query and calling "First" hits the database again every time. Dec 8, 2010 at 18:14
  • 1
    It gets worse when you have one-time iteration like reading from file... So Ani's answer from other thread looks the best. Dec 8, 2010 at 18:20
  • @Eric - C'mon. There's nothing wrong with hitting the database three times for each element...:-P Dec 8, 2010 at 18:24
4

This may be late, but an extension that works for value and reference types alike based on Eric's answer:

public static partial class Extensions
{
    public static Nullable<T> Unanimous<T>(this IEnumerable<Nullable<T>> sequence, Nullable<T> other, IEqualityComparer comparer = null)  where T : struct, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (Nullable<T>)first ?? other;
    }

    public static T Unanimous<T>(this IEnumerable<T> sequence, T other, IEqualityComparer comparer = null)  where T : class, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (T)first ?? other;
    }
}
2
public int GetResult(List<int> list){
int first = list.First();
return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
}
1

An alternative to using LINQ:

var set = new HashSet<int>(values);
return (1 == set.Count) ? values.First() : otherValue;

I have found using HashSet<T> is quicker for lists of up to ~ 6,000 integers compared with:

var value1 = items.First();
return values.All(v => v == value1) ? value1: otherValue;
5
  • Firstly this may create lots of garbage. Also it is less clear then the other LINQ answers, but slower then the extension method answers. Feb 3, 2015 at 14:53
  • 1
    True. However, the won't be much garbage if we are talking about determining whether a small set of values are all the same. When I ran this and a LINQ statement in LINQPad for a small set of values, HashSet was quicker (timed using Stopwatch class). Feb 3, 2015 at 18:09
  • If you run it in a release build from the command line you will may get different results. Feb 3, 2015 at 22:39
  • 1
    Created a console application and find that HashSet<T> is initially quicker than using the LINQ statements in my answer. However, if I do this in a loop, then LINQ is quicker. Mar 25, 2015 at 18:30
  • The big issue with this solution is that if you're using your custom classes, you have to implement your own GetHashCode(), which is difficult to do correctly See: stackoverflow.com/a/371348/2607840 for more details.
    – Cameron
    Nov 10, 2016 at 14:59
-2

A slight variation on the above simplified approach.

var result = yyy.Distinct().Count() == yyy.Count();

1
  • 5
    This is exactly the other way round. This will check that every element in the list is Unique. May 9, 2018 at 9:53
-5

If a array is of type multidimension like below then we have to write below linq to check the data.

example: here elements are 0 and i am checking all values are 0 or not.
ip1=
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

    var value=ip1[0][0];  //got the first index value
    var equalValue = ip1.Any(x=>x.Any(xy=>xy.Equals()));  //check with all elements value 
    if(equalValue)//returns true or false  
    {  
    return "Same Numbers";  
    }else{  
    return "Different Numbers";   
    }
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.