【发布时间】:2011-03-15 03:21:42
【问题描述】:
我有一个 List(Of DateTime) 项目。如何使用 LINQ 查询检查所有项目是否相同?在任何给定时间,列表中可能有 1、2、20、50 或 100 个项目。
【问题讨论】:
标签: c# vb.net list linq-to-objects
我有一个 List(Of DateTime) 项目。如何使用 LINQ 查询检查所有项目是否相同?在任何给定时间,列表中可能有 1、2、20、50 或 100 个项目。
【问题讨论】:
标签: c# vb.net list linq-to-objects
像这样:
if (list.Distinct().Skip(1).Any())
或者
if (list.Any(o => o != list[0]))
(可能更快)
【讨论】:
list.Distinct().Skip(1).Any() 与 list.Distinct().Count != 1 没有什么不同,对吧?
!(list.Any(o => o != list[0])),如果没有与第一个不同的项目,即如果它们都相同
Any() 用于查找至少 1 个匹配项,而 All() 用于确保所有项目匹配。在任何一种情况下,如果在 All 中遇到不匹配或在 Any 中找到匹配,它们将停止迭代。所以!(list.Any(o => o != list[0])); 和list.All(o => o == list[0]); 将始终具有相同的迭代次数。因此,两者的执行时间大致相同。附言你是对的,因为 list.Distinct().Skip(1).Any() 类似于 list.Distinct().Count != 1 只是要知道 Count 可能比具有 > 1 个元素的 Any(甚至可能在这种情况下)慢。
我创建了简单的扩展方法,主要是为了可读性,它适用于任何 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;
}
【讨论】:
我的变种:
var numUniques = 1;
var result = list.Distinct().Count() == numUniques;
【讨论】:
这也是一个选项:
if (list.TrueForAll(i => i.Equals(list.FirstOrDefault())))
它比 if (list.Distinct().Skip(1).Any()) 快,并且性能类似于
if (list.Any(o => o != list[0])),不过差别不大,建议用可读性更强的。
【讨论】:
VB.NET 版本:
If list.Distinct().Skip(1).Any() Then
或者
If list.Any(Function(d) d <> list(0)) Then
【讨论】: