ソースコード
using System;
using System.Collections.Generic;
using System.Linq;
public static class IEnumerableExt
{
public static bool HasDuplication<TKey, TSource>
(
this IEnumerable<TSource> self,
Func<TSource, TKey> keySelector
)
{
return self
.GroupBy( keySelector )
.Any( x => 1 < x.Count() )
;
}
public static bool HasDuplication<TSource>
(
this IEnumerable<TSource> self
)
{
return self
.GroupBy( x => x )
.Any( x => 1 < x.Count() )
;
}
使用例
var list1 = new[] { 1, 2, 3 };
Debug.Log( list1.HasDuplication() );
var list2 = new[] { 1, 1, 1 };
Debug.Log( list2.HasDuplication() );
var list3 = new[]
{
( Id: 1, Name: "フシギダネ" ),
( Id: 2, Name: "フシギソウ" ),
( Id: 3, Name: "フシギバナ" ),
};
Debug.Log( list3.HasDuplication( x => x.Id ) );
var list4 = new[]
{
( Id: 1, Name: "フシギダネ" ),
( Id: 1, Name: "フシギダネ" ),
( Id: 1, Name: "フシギダネ" ),
};
Debug.Log( list4.HasDuplication( x => x.Id ) );
関連記事