1

I have a list : List<NXRoute> NXRouteList = new List<NXRoute>();

Inside this list, each "NXRoute" has a properties :

  • DestinationSignal (it's a string)
  • Path which represents a list (List<Path> pathList = new List<Path>();)

I would like to compare the elements of NXRouteList according to the property DestinationSignal, so:

  • If two elements with the same value of DestinationSignal are found

    ==> before deleting the duplicate element, I would like to add the elements of its Path list to thePath list of the other element (the one that has the same DestinationSignal

Being new to c# programming I don't really know how to implement this

AmirDevouche
  • 45
  • 1
  • 6
  • 2
    Unfortunately stackoverflow it is not a codegenerator, but you can imagine that you have to make 2 loops for compare each item of the list with the forward items. Inside you have to make a comparison of your property. – Brank Victoria Jan 31 '19 at 15:20
  • GroupBy + Select or IEqualityComparer. you should find related question with "distinct list object c#" – xdtTransform Jan 31 '19 at 15:23
  • @BrankVictoria I think overriding Equals and GetHashCode for Path and using simple Union on lists is enough. – LukaszBalazy Jan 31 '19 at 15:23
  • You can use LINQ to easily do that, google it abit. – Shlomi Bazel Jan 31 '19 at 15:23
  • Possible duplicate of [How to merge group by list in LINQ](https://stackoverflow.com/questions/38696623/how-to-merge-group-by-list-in-linq) – xdtTransform Jan 31 '19 at 15:49

2 Answers2

1

Maybe this code could help you. This method creates new list of NXRoutes with no duplicates on DestinationSignal. Call to .SelectMany method aggregates all Paths for duplicated DestinationSignal values into 1 new NXRoute record.

public List<NXRoute> GetAllNXRoutesWithoutDuplicates(List<NXRoute> list)
{
    var nxRoutesWithSameDestinationSignals = list.GroupBy(x => x.DestinationSignal);
    return nxRoutesWithSameDestinationSignals.Select(group => new NXRoute
    {
        DestinationSignal = group.Key,
        Path = group.SelectMany(x => x.Path).ToList()
    }).ToList();
}
Lech Osiński
  • 512
  • 7
  • 14
0

I would implement IComparable for NXRouteList. You can implement CompareTo to check that the DestinationSignal properties of both instances are equal.

Lews Therin
  • 3,707
  • 2
  • 27
  • 53
  • It seems like the author doesn't really want to make a custom comparer, but just filter his input from duplicates (and aggregate the Paths those duplicates contain into 1 record). – Lech Osiński Jan 31 '19 at 15:32