2012-12-16 169 views
0

我有一个ArrayList的对象。其中一些对象属于这一类:如何检查对象的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是否包含与我的对象相同的对象。

那么,我该怎么做呢?

+0

为什么要使用泛型列表''在你的类。但是让你的类保持非泛型'AraryList'? – abatishchev

回答

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

我希望这是它:)

1

随着列表是您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)); 
+0

请注意,偏移量和单词本身是列表,所以这项工作? – AyaZoghby

+0

另外,我无法将我的ArrayLis转换为List,因为它有多种类型的对象。 – AyaZoghby

相关问题