C# 去集合中重複的物件
阿新 • • 發佈:2019-02-19
///
///去集合重複物件的類
///
public static IEnumerable<TSource> DistinctBys<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
HashSet<TKey> hashSet = new HashSet<TKey>();
foreach (TSource element in source)
{
if (hashSet.Add(keySelector(element))) { yield return element; }
}
///去集合重複物件的類
///
public static IEnumerable<TSource> DistinctBys<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
HashSet<TKey> hashSet = new HashSet<TKey>();
foreach (TSource element in source)
{
if (hashSet.Add(keySelector(element))) { yield return element; }
}
}
例如:
IList<TeachesInfo> tf_Class = tf.DistinctBys(e => new { e.GradeID, e.SchoolClassID }).ToList();//當前年級下唯一的班級