.NET-list擴展方法Distinct去重


原文鏈接:https://blog.csdn.net/daigualu/article/details/70800012

 

.NET中list的擴展方法Distinct可以去掉重復的元素,分別總結默認去重和自定義去重。

 class Program
    {
        static void Main(string[] args)
        {
            //Distinct去重

            //默認去重
            List<int> list1 = new List<int> {3, 9, 2, 3, 9};
            List<int> list2 = list1.Distinct().ToList(); //出去重復元素,列表變為{3,9,2}

            //自定義去重
            List<Test> list3 = new List<Test>();
            list3.Add(new Test(){Data=3});
            list3.Add(new Test() { Data = 9 });
            list3.Add(new Test() { Data = 2 });
            list3.Add(new Test() { Data = 3 });
            list3.Add(new Test() { Data = 9 });
            List<Test> list4 = list3.Distinct(new TestDuplicateDefine()).ToList();//變為3項
        }

        public class Test
        {
            public int Data { get; set; }
        }

        public class TestDuplicateDefine: IEqualityComparer<Test>
        {
            public bool Equals(Test x, Test y)
            {
                return x.Data == y.Data;
            }

            public int GetHashCode(Test obj)
            {
                return obj.ToString().GetHashCode();
            }
        }

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM