목록 (날짜 시간 중) 항목이 있습니다. 모든 항목이 LINQ 쿼리와 동일한 지 어떻게 확인할 수 있습니까? 주어진 시간에 목록에 1, 2, 20, 50 또는 100 개의 항목이있을 수 있습니다.목록의 모든 항목이 같은지 확인하십시오.
감사
이 같이목록 (날짜 시간 중) 항목이 있습니다. 모든 항목이 LINQ 쿼리와 동일한 지 어떻게 확인할 수 있습니까? 주어진 시간에 목록에 1, 2, 20, 50 또는 100 개의 항목이있을 수 있습니다.목록의 모든 항목이 같은지 확인하십시오.
감사
이 같이:
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
0
또는
나는 주로 어떤을 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;
}
이도 옵션입니다 :
if (list.TrueForAll(i => i.Equals(list.FirstOrDefault())))
그것은 if (list.Distinct().Skip(1).Any())
보다 더 빨리, 그리고 if (list.Any(o => o != list[0]))
그러나 차이로 유사하게 수행 중요하지 않으므로 좀 더 읽기 쉬운 것을 사용하는 것이 좋습니다.
잠재적으로 "Any"대신 "All"로 읽기 쉽습니다. 목록 액세스를 수행 할 수없는 경우 (IEnumerable) [0] 대신 First()를 사용할 수도 있습니다. (list.All (o => o == list.First())) {...} –
'list.Distinct(). 건너 뛰기 (1) .Any()'는'list.Distinct). 계산 = = 1' 맞죠? –
@GraemeWicksted Any()의 전체 요점은 일치하지 않는 항목이 하나있는 경우 더 빠릅니다. 그런 다음 목록 평가를 중단합니다. 무엇보다 약간 더 명확한 것은'! (list.Any (o => o! = list [0]))'입니다. 첫 번째 아이템과 다른 아이템이 없다면 true입니다. 즉, 모두 같다면 –