如何使用bool contains打印出排序列表中的项和键的值?我只想打印出那个匹配钥匙的那个。提前致谢!
正如你所说,我宣布了排序列表中我有一个类,而一个艺术家的密钥来自gui的文本文本。
我们这样说
string artsearch = something;
bool contains = list.ContainsKet(artsearch);
SortedList<string, Artist> list = new SortedList<string, Artist>();
Artist a = new Artist(artist, members, albm1);
a.Name = artist;
a.Members = members;
list.Add(artist, a);
public class Artist : IComparable
{
public string name;
public string members;
public string album;
public Guid artistID;
public LinkListGen<string> albums;
public Artist()
{
artistID = new Guid();
}
public Artist(string name, string members, LinkListGen<string> albums)
{
this.name = name;
this.members = members;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Albums
{
get { return album; }
set { album = value; }
}
public string Members
{
get { return members; }
set { members = value; }
}
public int CompareTo(object obj)
{
if (obj is Artist)
{
Artist other = (Artist)obj;
return name.CompareTo(other.name);
}
if (obj is string)
{
string other = (string)obj;
return members.CompareTo(other);
}
else
{
return -999;
}
}
}
答案 0 :(得分:4)
您可以使用索引器获取值:
if(contains)
{
Console.WriteLine("{0} -> {1}", artsearch, list[artsearch]);
}
您可以使用TryGetValue
:
Artist value;
if(list.TryGetValue(artsearch, out value))
{
Console.WriteLine("{0} -> {1}", artsearch, value);
}
请注意,这适用于任何实现IDictionary<TKey, TValue>
的类,而不仅仅是SortedList<TKey, TValue>
。