By Saif Khan


2011-03-15 03:21:42 8 Comments

I have a List(Of DateTime) items. How can I check if all the items are the same with a LINQ query? At any given time there could be 1, 2, 20, 50 or 100 items in the list.

Thanks

5 comments

@VBorisoff 2019-05-05 16:00:58

My variant:

var numUniques = 1;
var result = list.Distinct().Count() == numUniques;

@KungFury 2017-11-24 08:48:22

This is an option, too:

 if (list.TrueForAll(i => i.Equals(list.FirstOrDefault())))

It is faster than if (list.Distinct().Skip(1).Any()) , and performs similarly as if (list.Any(o => o != list[0])), however, the difference is not significant, so I suggest using the more readable one.

@MSkuta 2016-03-07 09:16:03

I created simple extension method mainly for readability that works on any IEnumerable.

if (items.AreAllSame()) ...

And the method implementation:

    /// <summary>
    ///   Checks whether all items in the enumerable are same (Uses <see cref="object.Equals(object)" /> to check for equality)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="enumerable">The enumerable.</param>
    /// <returns>
    ///   Returns true if there is 0 or 1 item in the enumerable or if all items in the enumerable are same (equal to
    ///   each other) otherwise false.
    /// </returns>
    public static bool AreAllSame<T>(this IEnumerable<T> enumerable)
    {
        if (enumerable == null) throw new ArgumentNullException(nameof(enumerable));

        using (var enumerator = enumerable.GetEnumerator())
        {
            var toCompare = default(T);
            if (enumerator.MoveNext())
            {
                toCompare = enumerator.Current;
            }

            while (enumerator.MoveNext())
            {
                if (toCompare != null && !toCompare.Equals(enumerator.Current))
                {
                    return false;
                }
            }
        }

        return true;
    }

@jor 2013-07-24 12:57:30

VB.NET version:

If list.Distinct().Skip(1).Any() Then

Or

If list.Any(Function(d) d <> list(0)) Then

@SLaks 2011-03-15 03:25:26

Like this:

if (list.Distinct().Skip(1).Any())

Or

if (list.Any(o => o != list[0]))

(which is probably faster)

@Graeme Wicksted 2014-09-08 21:00:57

Potentially easier to read with "All" instead of "Any". You may also want to use First() instead of [0] in case list access cannot be performed (IEnumerable). if (list.All(o => o == list.First())) { ... }

@Simon_Weaver 2016-09-17 19:15:49

list.Distinct().Skip(1).Any() is no different than list.Distinct().Count != 1 right?

@Simon_Weaver 2016-09-17 19:21:44

@GraemeWicksted the whole point of Any() is to be faster if one item is found that DOESN'T match. Then you stop evaluating the list. What IS slightly clearer though is !(list.Any(o => o != list[0])) which is true if there are no items that are different from the first one - i.e. if they're all the same

@Graeme Wicksted 2016-09-19 00:57:22

@Simon_Weaver Any() is used to find at least 1 match while All() is used to ensure all items match. In either case, if a non-match is encountered in All or a match is found in Any, they will halt iteration. So !(list.Any(o => o != list[0])); and list.All(o => o == list[0]); will always have the same iteration count. Thus both will have about the same execution time. P.S. You are correct, in that list.Distinct().Skip(1).Any() is analogous to list.Distinct().Count != 1 just be aware Count can be slower than Any (possibly even in this case) with > 1 element.

@Lewis Cianci 2018-08-13 22:52:47

Out of all the examples provided, list.Distinct().Count != 1 is the most readable (in my opinion)

Related Questions

Sponsored Content

45 Answered Questions

[SOLVED] Removing duplicates in lists

39 Answered Questions

[SOLVED] How to make a flat list out of list of lists

15 Answered Questions

[SOLVED] How to randomly select an item from a list?

  • 2008-11-20 18:42:21
  • Ray Vega
  • 1244897 View
  • 1564 Score
  • 15 Answer
  • Tags:   python list random

20 Answered Questions

30 Answered Questions

[SOLVED] How do I check if a list is empty?

  • 2008-09-10 06:20:11
  • Ray Vega
  • 2257136 View
  • 3237 Score
  • 30 Answer
  • Tags:   python list

15 Answered Questions

[SOLVED] How to clone or copy a list?

28 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3277835 View
  • 2697 Score
  • 28 Answer
  • Tags:   python list indexing

21 Answered Questions

[SOLVED] How can I count the occurrences of a list item?

  • 2010-04-08 13:30:00
  • weakish
  • 1364650 View
  • 1319 Score
  • 21 Answer
  • Tags:   python list count

25 Answered Questions

[SOLVED] Why not inherit from List<T>?

15 Answered Questions

[SOLVED] Using LINQ to remove elements from a List<T>

  • 2009-05-12 15:56:24
  • TK.
  • 531918 View
  • 603 Score
  • 15 Answer
  • Tags:   c# .net linq list

Sponsored Content