C# List 对象去重

扩展类

 

  public static class ObjectExtensions
    {    
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
    }

对象:

    /// <summary>
    /// 返回题目数据
    /// </summary>
    [Serializable]
    public class QuestionResult
    {
        /// <summary>
        /// 编号
        /// </summary>
        public long Id { get; set; }

        /// <summary>
        /// 题目内容
        /// </summary>
        public string Title { get; set; }
 
    }

  

用例:

list.DistinctBy(e => new { e.Id }).ToList();

 

posted @ 2020-06-15 10:49  wfpanskxin  阅读(576)  评论(0编辑  收藏  举报