0

I have an ArrayList of objects. 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.

So, how can I do that?

1
  • Why do use generic List<T> in your class. But keep your classes in non-generic AraryList? Dec 16, 2012 at 22:49

2 Answers 2

1
if (words.Contains(myObject))

ArrayList has a method called Contains which checks if the Object has the same Reference than the one you have. If you want to check if the value is the same, but a different Reference, you have to Code:

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

I hope this is it :)

1

With list being your ArrayList and item being the NewCompactSimilar you are searching for:

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:

list.OfType<NewCompactSimilar>().
                FirstOrDefault(o => o.DeepEquals(item));
2
  • Note that offset and words themselves are Lists, so would this work?
    – AyaZoghby
    Dec 16, 2012 at 22:42
  • Also, I can't convert my ArrayLis to List, since it have multiple types of objects.
    – AyaZoghby
    Dec 16, 2012 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.