从List返回匹配<keyvaluepair <string,string>&gt; </keyvaluepair <string,string>

时间:2009-11-24 22:44:21

标签: c# list foreach

我目前有一个班级使用KeyValuePairList来存储一系列音轨,格式为Key = track,Value = artist。

我正在尝试提供搜索特定曲目的方法,如果有任何匹配,则返回整个匹配的CD。

这是我到目前为止的尝试:

public CompilationCD FindTrackInComCD(string track)
{
    CompilationCD temp = new CompilationCD();

    List<CD> tempComCols = _cdCollection.FindAll(delegate(CD cd)
    { return cd.GetType() == temp.GetType(); });

    foreach (KeyValuePair<string, string> comCD in tempComCols)
    {
        if (comCD.Key.Contains(track))
        {
            return comCD;
        }
    }

    throw new ArgumentException("No matches found");
}

我有一个CD类型的CD集合(List<CD>),因此我通过将它与临时列表进行比较来创建一个适合类型的新List<>

编译时出现以下错误:

Cannot convert type 'CDCollection.CD' to System.Collections.Generic.KeyValuePair<string,string>'

Cannot implicitly convert type 'System.Collections.Generic.KeyValuePair<string,string>'

(CDCollection是我的项目命名空间,CD / CompilationCD是类)

对不起这个看似像我之前问过的类似问题。我尝试使用之前给出的方法,但我有点难过;我没有经常使用List<>KeyValuePair

这是CD类:

using System;

使用System.Collections; 使用System.Collections.Generic; 使用System.Linq; 使用System.Text;

命名空间CDCollection {     公共课CD     {         #region Fields         private readonly string _artist;         private readonly string _album;         private List _track = new List();         #endregion

    #region Constructors
    public CD()
    {
        _artist = "";
        _album = "";
        _track = null;
    }

    public CD(string albumName)
    {
        _album = albumName;
    }

    public CD(string artistName, string albumName)
    {
        _artist = artistName;
        _album = albumName;
    }

    #endregion

    #region Properties
    /// <summary>
    /// Get/Set Artist Name
    /// </summary>
    public virtual string Artist
    {
        get
        {
            return _artist;
        }
        set
        {
            value = _artist;
        }
    }

    /// <summary>
    /// Get/Set Album
    /// </summary>
    public string Album
    {
        get
        {
            return _album;
        }
        set
        {
            value = _album;
        }
    }

    /// <summary>
    /// Get/Set Track Name
    /// </summary>
    public virtual List<string> Track
    {
        get
        {
            return _track;
        }
        set
        {
            value = _track;
        }
    }

    #endregion

    #region ToString()
    /// <summary>
    /// Custom ToString() Method
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        //Create new StringBuilder object
        StringBuilder sb = new StringBuilder();

        sb.Append("Artist Name");

        //Display error if Artist is not available
        if (_artist == null || _artist == "")
        {
            sb.Append("\nNo Artist Entered");
        }
        else
        {
            sb.Append("\n" + this._artist);
        }

        sb.Append("\n");
        sb.Append("\nAlbum Name");

        //Display error if Album is not available
        if (_album == null || _album == "")
        {
            sb.Append("\nNo Album Entered");
        }
        else
        {
            sb.Append("\n" + this._album);
        }

        sb.Append("\n");
        sb.Append("\nTrack Name");
        sb.Append("\n");

        //Iterate through all tracks stored in list
        foreach (string trackName in _track)
        {
            //Print each artist
            sb.Append("\n" + trackName);
        }

        sb.Append("\nEnd of CD Record.........");

        return sb.ToString();
    }

    #endregion
}

}

这是CompilationCD类:

using System;

使用System.Collections.Generic; 使用System.Linq; 使用System.Text;

命名空间CDCollection {     公共类编译CD:CD     {         #region Fields

    private readonly string _artist;
    private readonly string _album;
    private List<KeyValuePair<string,string>> _tracks = new List<KeyValuePair<string,string>>();

    //List<KeyValuePair> Reference.
    //http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.85).aspx

    #endregion

    #region Constructors

    public CompilationCD()
    {
        _album = "";
        _artist = "Various Artists";
    }

    public CompilationCD(string albumName):base(albumName)
    {
        _album = albumName;
        _artist = "Various Artists";
    }

    #endregion

    public void AddTracks(string track, string artist)
    {
        _tracks.Add(new KeyValuePair<string, string>(track, artist));
    }

    #region Properties

    public override string Artist
    {
        get
        {
            return this._artist;
        }
    }

    public new List<KeyValuePair<string,string>> Track
    {
        get
        {
            return _tracks;
        }
        set
        {
            _tracks = value;
        }
    }


    #endregion

    #region ToString()

    //TEST
    public override string ToString()
    {
        //Create new StringBuilder object
        StringBuilder sb = new StringBuilder();

        sb.Append("Artist Name");

        //Display error if Artist is not available
        if (_artist == null || _artist == "")
        {
            sb.Append("\nNo Artist Entered");
        }
        else
        {
            sb.Append("\n" + this._artist);
        }

        sb.Append("\n");
        sb.Append("\nAlbum Name");

        //Display error if Album is not available
        if (base.Album == null || base.Album == "")
        {
            sb.Append("\nNo Album Entered");
        }
        else
        {
            sb.Append("\n" + base.Album);
        }

        sb.Append("\n");
        sb.Append("\nTrack Name");
        sb.Append("\n");

        ////Iterate through all tracks stored in list
        //foreach (string trackName in base.Track)
        //{
        //    //Print each artist
        //    sb.Append("\n" + trackName);
        //}

        for(int i = 0; i <= _tracks.Count; i++)
        {
            string track = _tracks[i].Key;
            string artist = _tracks[i].Value;

            sb.Append("\nTrack");
            sb.Append(track);
            sb.Append("\nArtist");
            sb.Append(artist);
        }

        sb.Append("\nEnd of Compilation CD Record.........");

        return sb.ToString();
    }

    #endregion
}

}

我有严格的规则,这意味着我必须从CD继承以创建我的CompilationCD以及使用List&gt;对于我的曲目集,它需要同时拥有曲目和艺术家。我知道疯狂= /

此外,我必须将所有类型的CD存储在CD(List)类型的列表中。

8 个答案:

答案 0 :(得分:5)

为什么不使用字典?它们是键值对的列表,但可以通过键轻松访问。

答案 1 :(得分:2)

问题出在你的foreach循环中。 tempComColsList<CD>,但comCDKeyValuePair<string, string>。因此,您的循环会导致无效的类型转换。

不幸的是,由于我们不知道CD类(接口?)是什么样的,我无法根据其属性建议修复。

编辑:以下可能是您方法的更好版本(但是,我没有正确调试):

public CompilationCD FindTrackInComCD(string track)
{
    CompilationCD temp = new CompilationCD();

    temp = _cdCollection.Where(cd => cd is CompilationCD)
                        .Cast<CompilationCD>()
                        .Where(com_cd => com_cd.Tracks.ContainsKey(track))
                        .FirstOrDefault();

    if (temp != null)
        return temp;
    else throw new ArgumentException("No matches found");
}

您无法将CompilationCD转换为KeyValuePair<string, string>,因此我们只是直接使用CompilationCD类。我们可以将搜索曲目列表的责任转移到IEnumerable<T>提供的System.Linq扩展方法,这使得此方法非常简单。

答案 2 :(得分:0)

那是因为tempComCols将返回CD而不是KeyValuePair<string, string>

答案 3 :(得分:0)

您的List不包含KeyValuePairs,因此您无法像它那样循环播放它。尝试这样的事情:

foreach (CD comCD in tempComCols)
{
    if (comCD.MyKeyValueProp.Key.Contains(track))
    {
        return comCD;
    }
}

但正如McKay所说,如果你的CD课程除了封装KeyValuePair之外什么都不做,那么Dictionary会更容易。

答案 4 :(得分:0)

tempComCols是CD项列表:List<CD> tempComCols ...,您希望迭代IEnumerable类型的内容:foreach (KeyValuePair<string, string> comCD in tempComCols)

答案 5 :(得分:0)

您要枚举List<CD>并分配给KeyValuePair<string, string>

您可以使用C#3中的LINQ重写您的方法,如下所示:

public CompilationCD FindTrackInComCD(string track) {
    return _cdCollection.OfType<CompilationCD>().FirstOrDefault(cd => cd.Name.Contains(track, StringComparison.CurrentCultureIgnoreCase));
}

顺便说一下,您可以通过撰写System.Type来获取CompilationCD typeof(CompilationCD)对象;您无需致电GetType()

答案 6 :(得分:0)

  1. 你可以使用:

    {cd is CompilationCD};
    

    而不是

    { return cd.GetType() == temp.GetType(); });
    
  2. 如果我理解正确并且CD是某种字典,您可以将该函数重写为:

    public CompilationCD FindTrackInComCD(string track)
    {
        return (CompilationCD)_cdCollection.Find(delegate(CD cd)
        { return (cd is CompilationCD) && (cd.Contains(track))});
    }
    

答案 7 :(得分:0)