Sai*_*han 55 c# vb.net linq-to-objects list
我有一个List(Of DateTime)项目.如何检查所有项目是否与LINQ查询相同?在任何给定时间,列表中可能有1,2,20,50或100个项目.
谢谢
SLa*_*aks 95
像这样:
if (list.Distinct().Skip(1).Any())
Run Code Online (Sandbox Code Playgroud)
要么
if (list.Any(o => o != list[0]))
Run Code Online (Sandbox Code Playgroud)
(这可能更快)
我创建了简单的扩展方法,主要是为了可读性,适用于任何IEnumerable.
if (items.AreAllSame()) ...
Run Code Online (Sandbox Code Playgroud)
方法实现:
/// <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;
}
Run Code Online (Sandbox Code Playgroud)
我的变种:
var numUniques = 1;
var result = list.Distinct().Count() == numUniques;
Run Code Online (Sandbox Code Playgroud)
小智 5
这也是一种选择:
if (list.TrueForAll(i => i.Equals(list.FirstOrDefault())))
Run Code Online (Sandbox Code Playgroud)
它比 快if (list.Distinct().Skip(1).Any()),并且性能与 相似
if (list.Any(o => o != list[0])),但是,差异并不显着,所以我建议使用更易读的一个。
| 归档时间: |
|
| 查看次数: |
46994 次 |
| 最近记录: |