Custom Contains for List<ReferenceObject> c#

ぐ巨炮叔叔 提交于 2020-01-04 16:57:25

问题


I'm trying to use List.Contains in a List My objects to compare come from a Service Reference in C# and their Equals method doesn't suit my needs.

I've been looking into IEquatables or on how to override my Equals method in an objet I'm "given" but I can't seem to find a solution for this. Does some one know an efficient way to do this?

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");
        }

回答1:


You could write your own Contains using the LINQ Any extension method:

if (this.logList.Any(x => YourCompareMethod(x, commitItem)))
{ }

The Any will check if any call to the lambda expression will result in true.

Your YourCompareMethod should look like:

private bool YourCompareMethod(CommitItem a, CommitItem b)
{
    // do your comparison
}



回答2:


It sounds like you just want to implement IEqualityComparer<ActivitiesActivity>:

public class ActivitiesActivityEqualityComparer
    : IEqualityComparer<ActivitiesActivity>
{
    public bool Equals(ActivitiesActivity x, ActivitiesActivity y)
    {
        ...
    }

    public int GetHashCode(ActivitiesActivity activity)
    {
        ...
    }
}

Then:

// Reuse this for multiple calls
var equalityComparer = new ActivitiesActivityEqualityComparer();
...
if (this.logList.Contains(commitItem, equalityComparer))

Once you've created the equality comparer, you can use that for all kinds of things, such as dictionaries with an activity as the key, LINQ operations like Distinct and Join, etc.



来源:https://stackoverflow.com/questions/29146416/custom-contains-for-listreferenceobject-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!