List< ReferenceObject>的自定义包含C# [英] Custom Contains for List<ReferenceObject> c#

查看:55
本文介绍了List< ReferenceObject>的自定义包含C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用List.包含在列表中 我要比较的对象来自C#中的Service Reference,它们的Equals方法不符合我的需求.

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.

我一直在研究IEquatables或如何在对象中重写我的Equals方法,这是给定的",但是我似乎找不到解决方案. 有人知道这样做的有效方法吗?

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

推荐答案

您可以使用LINQ

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

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

Any将检查对lambda表达式的任何调用是否会导致true.

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

您的YourCompareMethod应该如下所示:

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

这篇关于List&lt; ReferenceObject&gt;的自定义包含C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆