我正在尝试在List中使用List.Contains 我要比较的对象来自C#中的服务引用,它们的Equals方法不适合我的需要。
我一直在研究IEquatables或者如何在我给出的objet中覆盖我的Equals方法,但我似乎无法找到解决方案。 有人知道这样做的有效方法吗?
public void FilterNonExisting(List<ActivitiesActivity> commitActivitiesList)
{
// ActivitiesActivity is the object I'm given through a reference
List<int> itemsToDelete = new List<int>();
int commitCount = 0;
foreach (ActivitiesActivity commitItem in commitActivitiesList)
{
if (this.logList.Contains(commitItem)) // this is the part that doesn't work the way I want it to {
itemsToDelete.Add(commitCount);
}
commitCount++;
}
itemsToDelete.Reverse();
foreach (int item in itemsToDelete)
commitActivitiesList.RemoveAt(item);
if (commitActivitiesList.Count == 0)
{
throw new AllCommitedException("All lines had already been committed");
}
答案 0 :(得分:3)
听起来你只想实施IEqualityComparer<ActivitiesActivity>
:
public class ActivitiesActivityEqualityComparer
: IEqualityComparer<ActivitiesActivity>
{
public bool Equals(ActivitiesActivity x, ActivitiesActivity y)
{
...
}
public int GetHashCode(ActivitiesActivity activity)
{
...
}
}
然后:
// Reuse this for multiple calls
var equalityComparer = new ActivitiesActivityEqualityComparer();
...
if (this.logList.Contains(commitItem, equalityComparer))
一旦你创建了相等比较器,就可以将它用于各种事物,例如以活动为关键词的词典,LINQ操作,如Distinct
和Join
等。< / p>
答案 1 :(得分:-1)
您可以使用LINQ Any
扩展方法编写自己的Contains
:
if (this.logList.Any(x => YourCompareMethod(x, commitItem)))
{ }
Any
将检查对lambda表达式的任何调用是否会导致true
。
您的YourCompareMethod
应如下:
private bool YourCompareMethod(CommitItem a, CommitItem b)
{
// do your comparison
}