2012-12-16 171 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

相關問題