简体   繁体   中英

Remove duplicates from the list with lists as objects

I have one list with the class as a structure as below

   class cl
    {
        public string name1{ get; set; }
        public string name2{ get; set; }
        public string name3{ get; set; }
        public List<c2> c2List{ get; set; }
    }
   class c2
    {
        public string st1{ get; set; }
        public string str2{ get; set; }
    }

Now I have list of C1 class and i need to remove duplicates from that list can any one help me how can i do it

When referencing c2List, call it similarly to the below:

var distinctList = c1.c2List.Distinct();

(Assuming that c1 is instantiated further up the code)

I think this is what your after..

        var c2Items = new c2[] 
        {
            new c2 { st1 = "value 1", str2 = "value 2" },
            new c2 { st1 = "value 2", str2 = "value 1" },
            new c2 { st1 = "value 1", str2 = "value 2" }
        };

        var parent = new cl() { c2List = new List<c2>(c2Items) };

        IEnumerable<c2> distinctitems = 
            parent
                .c2List
                .GroupBy(o => new { o.st1, o.str2 })
                .Select(o => o.First());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM