简体   繁体   中英

How can I remove comma separated same values from list using c# linq

I have ac# Product list:

var mylist = new List<Person>{
   new Product{Id=1, Name="p-1", Colors="1,2"},
   new Product{Id=2, Name="p-2", Colors="2,1"},
   new Product{Id=3, Name="p-2", Colors="3,4,5"},
   new Product{Id=4, Name="p-2", Colors="4,5,3"}
}

If a product color "1,2" and another product colors is "2,1", these products are same colors. So I want to remove one of them (which doesn't matter). The final list will be like this:

var mylist = new List<Person>{
   new Product{Id=1, Name="p-1", Colors="1,2"},
   new Product{Id=3, Name="p-2", Colors="3,4,5"}
}

I could not remove same color products from list using c# linq. How can I do this?

You can split and sort the Colors, group by them and since you are saying it is not important which might get the first from each group (I assume List was a typo):

var mylist = new List<Product>{
    new Product{Id=1, Name="p-1", Colors="1,2"},
    new Product{Id=2, Name="p-2", Colors="2,1"},
    new Product{Id=3, Name="p-2", Colors="3,4,5"},
    new Product{Id=4, Name="p-2", Colors="4,5,3"}
    };

var result = mylist
    .GroupBy(m => string.Join(",",m.Colors.Split(',').Select(c => c.Trim()).OrderBy(c => c)))
    .Select(m => new Product {
        Id=m.First().Id, 
        Name=m.First().Name, 
        Colors=m.Key});

I added one property of string[] type in the person class to keep it simple. These comma separated values are of no use so this property will be useful in further processing as well.

        var persons = new List<Person>{
                                       new Person{Id=1, Name="p-1", Colors="1,2"},
                                       new Person{Id=2, Name="p-2", Colors="2,1"},
                                       new Person{Id=3, Name="p-2", Colors="3,4,5"},
                                       new Person{Id=4, Name="p-2", Colors="4,5,3"}
                                    };

        persons.ForEach(x => x.ColorList = x.Colors.Split(','));

        var distinctPerson = new List<Person>();
        foreach (var item in persons)
        {
            var isExist = distinctPerson.Any(x => x.ColorList.Intersect(item.ColorList).Any());
            if(!isExist)
            {
                distinctPerson.Add(item);
            }
        }

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