2010-07-10 45 views
1

我有兩個列表包含一個像標籤列表我需要找到排除和包含做更新操作如何找到區別因爲它們包含一個Tag對象。你可以使用包含列表中的標籤對象的Contains函數需要一些幫助。列表<>和包含使用asp.net 2.0排除和包含的場景比較使用asp.net 2.0

即時通訊使用asp.net 2.0,所以請如果你能幫助我用那種語言做它。

List<Tag> tag1 = new List<Tag>() 
tag1.Add(new Tag("Apples")); 
tag1.Add(new Tag("Oranges")); 
tag1.Add(new Tag("Pears")); 

List<Tag> tag2 = new List<Tag>() 
tag2.Add(new Tag("Apples")); 
tag2.Add(new Tag("Bananas")); 

txtExcluded.Text = list1; 
txtIncluded.Text = list2 

回答

4

您可以實現IEquatable<T>

public class Tag : IEquatable<Tag> 
{ 
    public Tag(string text) 
    { 
     Text = text; 
    } 
    public string Text { get; set; } 

    public bool Equals(Tag other) 
    { 
     return other != null && string.Equals(Text, other.Text); 
    } 

    public override bool Equals(object obj) 
    { 
     return Equals(obj as Tag); 
    } 

    public override int GetHashCode() 
    { 
     return (Text ?? string.Empty).GetHashCode(); 
    } 
} 

現在包含的方法可以工作是這樣的:

var list = new List<Tag>(new[] 
{ 
    new Tag("Apples"), 
    new Tag("Oranges"), 
    new Tag("Pears"), 
}); 

var tag = new Tag("Pears"); 
bool isContains = list.Contains(tag); // returns true 
+0

IS .NET 2.0 – ONYX 2010-07-10 09:20:23

+2

的IEquatable一部分。如果執行'IEquatable '你應該確實也覆蓋'Equals'和'GetHashCode' - 否則會出現混亂。 – 2010-07-10 09:24:04

+0

@馬克,非常好的評論,我會更新我的答案。 – 2010-07-10 09:25:18