【问题标题】:How to check if an ArrayList of objects contains my object?如何检查对象的 ArrayList 是否包含我的对象?
【发布时间】:2012-12-04 01:46:55
【问题描述】:

我有一个ArrayList 的对象。其中一些对象属于此类:

public class NewCompactSimilar
{
    public List<int> offsets;
    public List<String> words;
    public int pageID;

    public NewCompactSimilar()
    {
        offsets = new List<int>();
        words = new List<string>();          
    }
}

但列表也可以包含其他类的对象。

我需要检查我的ArrayList 是否包含与我的对象相同的对象。

那么,我该怎么做呢?

【问题讨论】:

  • 为什么要在课堂上使用通用List&lt;T&gt;。但是将您的课程保留在非泛型 AraryList?

标签: c# .net arraylist contains


【解决方案1】:
if (words.Contains(myObject))

ArrayList 有一个名为 Contains 的方法,该方法检查 Object 是否具有与您的引用相同的引用。如果要检查值是否相同,但引用不同,则必须编码:

private bool GetEqual(String myString)
{
    foreach (String word in words)
    {
         if (word.Equals(myString))
            return true;
    }
    return false;
}

我希望就是这样:)

【讨论】:

    【解决方案2】:

    列表是您的ArrayList,项目是您要搜索的NewCompactSimilar

    list.OfType<NewCompactSimilar>().
                    FirstOrDefault(o => o.offsets == item.offsets &&
                    o.words == item.words &&
                    o.pageID == item.pageID);
    

    要运行深度相等比较,请实现以下方法:

    public bool DeepEquals(NewCompactSimilar other)
    {
        return offsets.SequenceEqual(other.offsets) &&
                words.SequenceEqual(other.words) &&
                pageID == other.pageID;
    }
    

    然后使用以下 LINQ 链:

    list.OfType<NewCompactSimilar>().
                    FirstOrDefault(o => o.DeepEquals(item));
    

    【讨论】:

    • 请注意,offset 和 words 本身都是 Lists,这样可以吗?
    • 另外,我无法将我的 ArrayLis 转换为 List,因为它有多种类型的对象。
    猜你喜欢
    • 2021-04-27
    • 2013-04-22
    • 1970-01-01
    • 2012-10-17
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2020-06-07
    相关资源
    最近更新 更多