4

Possible Duplicate:
Check if all items are the same in a List

I have a list:

{string, string, string, string}

I need to check if all the items in this list are the same then return true, if not return false.

Can i do this with LINQ?

Community
  • 1
  • 1
hs2d
  • 6,027
  • 24
  • 64
  • 103

4 Answers4

22
var allAreSame = list.All(x => x == list.First());
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • 1
    Except that `list.First()` is called on every iteration so effectively the list is traversed twice? – David Clarke May 31 '18 at 01:52
  • @DavidClarke: Assuming this is LINQ to objects and `list` is just a materialized collection like a list or an array: As `list.First` returns the very first element, it doesn't traverse the list, so: no, the list is only traversed once. Speaking more general, however, you are correct: If `list` would be a non-materialized enumerable, every call to `First` would need to execute all the code (e.g. hitting the database or executing complex Where or OrderBy statements) to get at least the first element. In that case, it would be better, to call `list.First` once and store the result – Daniel Hilgarth May 31 '18 at 05:47
3
var allAreSame = list.Distinct().Count() == 1;

or a little more optimal

var allAreSame = list.Count == 0 || list.All(x => x == list[0]);
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • Actually, for compact lists of primitive types, and even short strings (abbreviations, simple words, etc) I'd have no argument against `list.Distinct().Count() == 1;` versus `list.All(current => current == list.First())` at least for readability's sake. – Arman Jan 21 '19 at 16:11
1

How about this:

    string[] s = { "same", "same", "same" };
    if (s.Where(x => x == s[0]).Count() == s.Length)
    {
        return true;
    }
CrazyDart
  • 3,803
  • 2
  • 23
  • 29
0
var hasIdenticalItems = list.Count() <= 1 || list.Distinct().Count() == 1;
CaffGeek
  • 21,856
  • 17
  • 100
  • 184