반응형
목록에서 모든 항목이 동일한 지 확인
List (Of DateTime) 항목이 있습니다. LINQ 쿼리에서 모든 항목이 동일한 지 어떻게 확인할 수 있습니까? 주어진 시간에 목록에 1, 2, 20, 50 또는 100 개의 항목이있을 수 있습니다.
감사
이렇게 :
if (list.Distinct().Skip(1).Any())
또는
if (list.Any(o => o != list[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;
}
VB.NET 버전 :
If list.Distinct().Skip(1).Any() Then
또는
If list.Any(Function(d) d <> list(0)) Then
이것도 옵션입니다.
if (list.TrueForAll(i => i.Equals(list.FirstOrDefault())))
보다 빠르며 if (list.Distinct().Skip(1).Any())
와 비슷하게 수행 if (list.Any(o => o != list[0]))
되지만 차이가 크지 않으므로 더 읽기 쉬운 것을 사용하는 것이 좋습니다.
내 변형 :
var numUniques = 1;
var result = list.Distinct().Count() == numUniques;
참조 URL : https://stackoverflow.com/questions/5307172/check-if-all-items-are-the-same-in-a-list
반응형
'developer tip' 카테고리의 다른 글
Spring @Transactional 읽기 전용 전파 (0) | 2021.01.07 |
---|---|
jQuery에서 console.log는 무엇입니까? (0) | 2021.01.07 |
git에서 빈 프로젝트에 분기 만들기 (0) | 2021.01.07 |
CoffeScript에서 두 개의 익명 함수를 인수로 전달하는 방법은 무엇입니까? (0) | 2021.01.07 |
DataFrame의 현재 파티션 수 가져 오기 (0) | 2021.01.06 |