gpt4 book ai didi

c# - 使用 distinct 删除重复项

转载 作者:行者123 更新时间:2023-12-04 09:32:26 26 4
gpt4 key购买 nike

我有一个类

class ShipmentsComparer : IEqualityComparer<Routes>
{
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);
}
和一个 IEnumerable
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).Distinct(new ShipmentsComparer()))
{
yield return new Shipments() { Arrival = item2.CarrierArrival, Departure = item2.CarrierDeparture, Issuer = item.Customer, Destination = item.ShipTo, LoadType = item.LoadType };
}
}
}
}
}
删除重复值,但我仍然在此处显示的项目源中得到重复值:
example
我怎样才能让它只显示每个承运人的到达时间之一?

最佳答案

似乎您正在获得重复项,因为您仅“区分”了内部循环结果。您需要使用 Distinct在调用方 - Shipmetns.Distinct(new ShipmentsComparer())或者如果你想在属性中过滤它们,你可以使用 HashSet :

class ActuallyShipmentsComparer : IEqualityComparer<Shipments>
{
//your logic
}

public IEnumerable <Shipments> Shipments
{
get
{
Debug.Print("Initiated");
var hash = new HashSet<Shipments>(new ActuallyShipmentsComparer());
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).Distinct(new ShipmentsComparer()))
{
var shipments = new Shipments { Arrival = item2.CarrierArrival, Departure = item2.CarrierDeparture, Issuer = item.Customer, Destination = item.ShipTo, LoadType = item.LoadType };
if(hash.Add(shipments))
{
yield return shipments;
}

}
}
}
}
}
或者用 Routes 试试同样的方法如果它们足以确定出货量相等:
    public IEnumerable<Shipments> Shipments
{
get
{
Debug.Print("Initiated");
var hash = new HashSet<Routes>(new ShipmentsComparer()); // rename ShipmentsComparer cause it is actually RoutesComparer
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))
{
if(hash.Add(item2))
{
yield return new Shipments { Arrival = item2.CarrierArrival, Departure = item2.CarrierDeparture, Issuer = item.Customer, Destination = item.ShipTo, LoadType = item.LoadType };
}
}
}
}
}
}

关于c# - 使用 distinct 删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62777420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com