有人给我解释一下:
我正在尝试从一个列表中删除具有包含在另一个字符串列表中的匹配 ID 的项目。
第一步如下:
我正在尝试从 myListingSyncIDs 中删除项目,其中 ListingNumber 与 lstListingsUpdatedIn24Hrs 中的 ListingNumbers 匹配。
[0] 处的项目等于 lstListingsUpdatedIn24Hrs 中的值,如第 2 步所示:
但是如Step3所示:Remove失败:
然后在执行 RemoveAll(func) Step4 之后:Remove 起作用了
有人解释为什么 Remove(item) 不起作用,拜托......
代码:
myListingSyncIDs.AddRange(myListingSync.Listings);
#region Remove Listing References Fetched In The Last 24Hrs
// Listing References Fetched In The Last 24Hrs
// These will be excluded to optimise the running of the App.
// Basically meaning that a complete sync of all listings
// will only be done once every 24hrs
// So that if this is run every hr, it will not slow down the most recent additions
List<String> lstListingsUpdatedIn24Hrs = DAL.PropertyPortalDAL.GetSahtWebserviceUpdatesIn24Hrs();
List<P24SyncService.ListingSyncItem> myListingsUpdatedIn24Hrs =
lstListingsUpdatedIn24Hrs.Select(p => new P24SyncService.ListingSyncItem()
{
ListingNumber = p,
Status = P24SyncService.ListingState.AddedModified
}).ToList();
foreach (P24SyncService.ListingSyncItem myLSI in myListingsUpdatedIn24Hrs)
{
myListingSyncIDs.Remove(myLSI);
}
myListingSyncIDs.RemoveAll(p => lstListingsUpdatedIn24Hrs.Contains(p.ListingNumber));
#endregion
ListingSyncItem 是:
public partial class ListingSyncItem {
private string listingNumberField;
private ListingState statusField;
/// <remarks/>
public string ListingNumber {
get {
return this.listingNumberField;
}
set {
this.listingNumberField = value;
}
}
/// <remarks/>
public ListingState Status {
get {
return this.statusField;
}
set {
this.statusField = value;
}
}
}
最佳答案
猜测,您的 ListingSyncItem
类型不会覆盖 Equals
, 所以 List<T>.Remove
不知道要删除的项目与列表中的项目“相等”。
简单地覆盖 Equals
和 GetHashCode
适本地(检查 ListNumber
和 Status
是否相等,据推测,并基于这些构建哈希码)应该可以解决问题。
对于 RemoveAll
,你提供了一个谓词。那不使用 ListingSyncItem.Equals
,这就是它起作用的原因。
关于c# - 列表<类型> 移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9496474/