Подтвердить что ты не робот

Проверьте, совпадают ли все элементы в списке

У меня есть элемент List (Of DateTime). Как я могу проверить, совпадают ли все элементы с запросом LINQ? В любой момент времени в списке могут быть 1, 2, 20, 50 или 100 элементов.

Спасибо

4b9b3361

Ответ 1

Вот так:

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

или

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

(что, вероятно, быстрее)

Ответ 2

Я создал простой метод расширения в основном для чтения, который работает на любом IEnumerable.

if (items.AreAllSame()) ...

И реализация метода:

    /// <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;
    }

Ответ 3

Это тоже вариант:

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

Это быстрее, чем if (list.Distinct().Skip(1).Any()), и выполняется аналогично if (list.Any(o => o != list[0])), однако разница не является существенной, поэтому я предлагаю использовать более читаемую.

Ответ 4

Версия VB.NET:

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

или

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

Ответ 5

Мой вариант:

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