-2

I have this list:

CustomerA

  • Cod123
  • Cod456

CustomerB

  • Cod456
  • Cod789

CustomerC

  • Cod888
  • Cod999

I want to return this using LINQ:

CustomerA

  • Cod123
  • Cod456

CustomerC

  • Cod888
  • Cod999

Because CustomerA and CustomerB have the same cod: Cod456

My classes:

    public class Customer
{
    public string Name { get; set; }
    public List<Cod> Cods { get; set; }
}

public class Cod
{
    public string Number { get; set; }
}

My attempt not build in GroupBy line.

            var customersOK = customersDuplicatedCods
                    .GroupBy(p => p.Cods.Number)
                    .Select(g => g.First())
                    .ToList();

1 Answers1

1

It sounds like you don't actually want them grouped, you just want duplicates removed.

This Q&A explains how to do that.

Basically you would create an IEqualityComparer<Customer>

class DistinctItemComparer : IEqualityComparer<Customer> 
{
    public bool Equals(Customer x, Customer y) 
    {
        return x.Cods.Intersect(y.Cods).Any();
    }

    public int GetHashCode(Customer obj) 
    {
        return 0;
    }
}

And call it by customers.Distinct(new DistinctItemComparer())

Community
  • 1
  • 1
Harrison Paine
  • 611
  • 5
  • 14