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();

 

C# List 对象去重

上一篇:C#--无边框窗体实现拖动、最大化、最小化、关闭(转)


下一篇:C# 如何在winform窗体自定义一个扁平化控件(转)