• 去除list集合中重复项的几种方法


    for (int i = 0; i < li2.Count; i++) //外循环是循环的次数
    {
    for (int j = li2.Count - 1 ; j > i; j--) //内循环是 外循环一次比较的次数
    {

    if (li2[i] == li2[j])
    {
    li2.RemoveAt(j);
    }

    }
    }

    去掉modelList中title重复的内容,不区分大小写

    class Program
        {
            static void Main(string[] args)
            {
                List<Model> modelList = new List<Model>() 
                { new Model() { ID = 1, Title = "abcde" },
                    new Model() { ID = 2, Title = "ABCDE" },
                    new Model(){ ID = 3, Title = "AbcdE" },
                    new Model() { ID = 4, Title = "A" }, 
                    new Model() { ID = 5, Title = "a" } 
                };
                Console.Read();
            }
        }
        public class Model
        {
            public int ID { get; set; }
            public string Title { get; set; }
        }

    解决方案一:这里比较的前提是对象的哈希代码相等。否则不会比较,因为哈希代码不相等。两个对象显然不相等

    //定义一个类继承IEqualityComparer接口
        public class ModelComparer : IEqualityComparer<Model>
        {
            public bool Equals(Model x, Model y)
            {
                return x.Title.ToUpper() == y.Title.ToUpper();
            }
            public int GetHashCode(Model obj)
            {
                return obj.Title.ToUpper().GetHashCode();
            }
        }
    modelList = modelList.Distinct(new ModelComparer()).ToList();

    解决方案二:

    var title = modelList.GroupBy(m => m.Title.ToLower().Trim()).Select(m => new { ID = m.FirstOrDefault().ID });
                modelList = modelList.Where(m => title.Select(mo => mo.ID).Contains(m.ID)).ToList(); 
                foreach (var item in modelList)
                {
                    Console.WriteLine(item.ID + "	" + item.Title);
                }
  • 相关阅读:
    第一次项目总结
    8.16 CSS知识点7
    2016y9m22d 博文分享
    2016y9m8d
    2016y9m7d
    2016y9m6d
    2016y9m5d
    2016.9.2博文分享!
    2016y8m16d
    2016y8m15d
  • 原文地址:https://www.cnblogs.com/xjt360/p/3891518.html
Copyright © 2020-2023  润新知