Skip to main content
 首页 » 编程设计

c#之List> 和 Contains 方案,使用 asp.net 2.0 比较 get excluded 和 included

2024年02月24日23Renyi-Fan

我有两个包含 Tag 对象的列表,例如 List 我需要查找排除项和包含项以执行更新操作如何找到它们之间的差异,因为它们包含一个 Tag 对象。您能否将 Contains 函数与列表中的 Tag 对象一起使用需要一些帮助。

我使用的是 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   

请您参考如下方法:

你可以实现 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(); 
    } 
} 

现在 Contains 方法可以像这样工作:

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