将IEnumerable字符串与SortedList字符串进行比较,字符串

时间:2014-03-31 15:29:09

标签: c# ienumerable sortedlist

我遇到了一个我无法解决的问题。 :-)我必须找到包含某个子字符串的所有值,然后我必须取回键和值对。我必须实现一个系统,我必须在其中制作一个SortedList,其中Albums是一个类字符串,当然是关键

Albums alb = new Albums();
SortedList<string, Albums> list1 = new SortedList<string, Albums>();

“专辑”类如下所示:

public class Albums : IComparable
{
    public string albname;
    public string name1;
    public string releasedate;
    public Guid albumID;

   public Albums()
    {
        albumID = new Guid();
    }



   public override string ToString()
   {
       return "Album: " + Albname + "\t" + Releasedate;
   }

   public Albums(string albname, string releasedate)
   {

       this.albname = albname;
       this.releasedate = releasedate;
   }

   public string Name1
   {
       get { return name1; }
       set { name1 = value; }
   }

    public string Albname
    {
        get { return albname; }
        set { albname = value; }
    }
   public string Releasedate
    {
        get { return releasedate; }
        set { releasedate = value; }
    }
    public int CompareTo(object obj)
    {
        if (obj is Albums)
        {
            Albums other = (Albums)obj;
            return albname.CompareTo(other.albname);
        }
       if (obj is string)
       {
           string other = (string)obj;
           return releasedate.CompareTo(releasedate);
       }


        else
        {
            return -999;
        }
    }
   }

我最后尝试将相册放入LinkedList:

LinkedList<string> albm1 = new LinkedList<string>();  

我确实设法使用IEnumerable找到包含子字符串的所有相册:

string albsearch = textBox16.Text;
IEnumerable<string> result = albm1.Where(s => s.Contains(albsearch));

但我不知道如何将结果与SortedList的值进行比较。我还尝试创建一个新的SortedList,其中包含字符串中的相册:

SortedList<string, string> list2 = new SortedList<string, string>();

任何建议都将不胜感激。提前谢谢!

2 个答案:

答案 0 :(得分:1)

当您枚举SortedList时,枚举中的每个项目都是键/值对。

我认为你想要的是:

Albums alb = new Albums();
SortedList<string, Albums> list1 = new SortedList<string, Albums>();

var foundItems = list1.Where(item => item.Key.Contains(albsearch));

或者,如果您想要搜索Album

var foundItems = list1.Where(item => item.Value.albname.Contains(albsearch));

当然,您可以搜索name1字段而不是相册名称,如果这是您想要的。

返回的每个项目都是键/值对。更准确地说,是KeyValuePair<string, Album>

答案 1 :(得分:0)

    [Test]
    public void Allbum_Search_Test()
    {
        var searchText = "TestA";
        var list1 = new SortedList<string, Albums>
        {
            {"TestAlbum1", new Albums("TestAlbum1","SomeDate")},
            {"TestAlbum2", new Albums("TestAlbum2","SomeDate")},
            {"OtherAlbum2", new Albums("OtherAlbum","SomeDate")}
        };

        var results = list1.Where(pair => pair.Key.Contains(searchText));

        Assert.That(results.Count(), Is.EqualTo(2));
    }

另一方面,我强烈推荐

  • 将字段设为私有
  • Albums重命名为Album
  • ReleaseDate类型更改为DateTime
  • Albname重命名为AlbumName