简体   繁体   English

如何检查对象的ArrayList是否包含我的对象?

[英]How to check if an ArrayList of objects contains my object?

I have an ArrayList of objects. 我有一个对象的ArrayList Some of these objects are of this class: 其中一些对象属于这一类:

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

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

But the list can also contain objects of other classes. 但是列表也可以包含其他类的对象。

I need to check if my ArrayList contains an object that is identical to my object. 我需要检查我的ArrayList包含一个与我的对象相同的对象。

So, how can I do that? 那么,我该怎么做呢?

if (words.Contains(myObject))

ArrayList has a method called Contains which checks if the Object has the same Reference than the one you have. ArrayList有一个名为Contains的方法,它检查Object是否具有与您拥有的Reference相同的Reference。 If you want to check if the value is the same, but a different Reference, you have to Code: 如果要检查值是否相同,但是不同的Reference,则必须使用Code:

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

I hope this is it :) 我希望这是它:)

With list being your ArrayList and item being the NewCompactSimilar you are searching for: 使用list作为您的ArrayList并且您正在搜索NewCompactSimilar

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

To run a deep equality comparison, implement the following method: 要运行深度相等比较,请实现以下方法:

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

Then use the following LINQ chain: 然后使用以下LINQ链:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM