I would like to know how you would remove duplicate rows from a IEnumerable. I have this code:
public IEnumerable <Shipments> Shipments
{
get
{
Debug.Print("Initiated");
foreach (var item in Loads)
{
if (item.ShipTo.Contains(" "))
{
foreach (var item2 in Routes.Where(d => d.DockCode == item.ShipTo.Substring(0, item.ShipTo.IndexOf(" ")) && d.CarrierDeparture.TimeOfDay == item.ShipTime.TimeOfDay))
{
yield return new Shipments() { Arrival = item2.CarrierArrival, Departure = item2.CarrierDeparture, Issuer = item.Customer, Destination = item.ShipTo, LoadType = item.LoadType };
}
}
}
}
}
which gives me this data using it as a item source
My goal is to only return new shipment if one that is the same doesn't exist. How would I go about doing that?
You could create a class that implements IEqualityComparer<Routes>
:
class RoutesComparer : IEqualityComparer<Routes>
{
// Might want to add null checks here.
public bool Equals(Routes route1, Routes route2) =>
route1.DockCode == route2.DockCode
&& route1.CarrierArrival == route2.CarrierArrival;
public int GetHashCode(Routes obj) =>
obj.DockCode.GetHashCode() ^ (obj.CarrierArrival.GetHashCode() * 13);
}
Then pass that to .Distinct()
.
foreach (var item2 in Routes.Where(d => d.DockCode == item.ShipTo.Substring(0, item.ShipTo.IndexOf(" "))
&& d.CarrierDeparture.TimeOfDay == item.ShipTime.TimeOfDay).Distinct(new RoutesComparer()))