0

我有一个由以下人员创建的列表:

List<Song> SongList = new List<Song>();

由一群人组成:

SongList.Add(new Song(songID, "Dirt", "Alice in Chains", "Rooster", "Rock", "02:32"));

歌曲的详细信息通过以下方式填充到 ListBox 中:

private void songTitle_TextChanged(object sender, EventArgs e)
{
    i = 0;

    for (; i < songTitle.Text.Length; i++)
    {
        songResultBox.Items.Clear();
        var songResult = from song in SongList
        where song.SongTitle != null && song.SongTitle.Length >= songTitle.Text.Length
            && songTitle.Text == song.SongTitle.Substring(0, i+1)
        select new { sId = song.SongID, album = song.SongAlbum, artist = song.SongArtist, title = song.SongTitle, 
            genre = song.SongGenre, length = song.SongLength };

        foreach (var item in songResult)
        {
            songResultBox.Items.Add(new Song(item.sId, item.album, item.artist, item.title, item.genre, item.length));
                songResultBox.DisplayMember = "FullName";
                songResultBox.ValueMember = "songID";
        }
    }
}

问题是:我将如何创建一个按钮(或实际上是 4 个)来获取 ListBox 'songResultBox' 的内容并按标题、专辑、艺术家、流派等对其内容进行排序。

4

1 回答 1

1

创建按钮,根据要排序的属性对其进行标记,向按钮添加单击事件,对项目进行排序(希望您已经维护了它们的列表),然后重新填充列表框:

private bool descendingSongTitleSort = false;
private bool descendingArtistSort = false;

// Artist button clicked event
private void artistButtonClicked(object sender, EventArgs args)
{
    Func<Song, IComparable> sortProp = (song => song.Artist);
    sortListBox(songResultBox, descendingArtistSort, sortProp);
    descendingSongTitleSort = false;
    descendingArtistSort = !descendingArtistSort;
}

// Title button clicked event
private void titleButtonClicked(object sender, EventArgs args)
{
    Func<Song, IComparable> sortProp = (song => song.Title);
    sortListBox(songResultBox, descendingSongTitleSort, sortProp);
    descendingSongTitleSort = !descendingSongTitleSort;
    descendingArtistSort = false;
}

// Sorting function
private void sortListBox(
    ListBox box, 
    bool descending, 
    Func<Song, IComparable> sortProperty)
{
    List<Song> items = new List<Song>();
    foreach (Object o in box.Items)
    {
        Song s = o as Song;
        items.Add(s);
    }
    box.Items.Clear();
    if(descending)
    {
        items = items.OrderByDescending(sortProperty).ToList(); 
    } 
    else 
    {
        items = items.OrderBy(sortProperty).ToList();
    }
    foreach(Song s in items)
    {
        box.Items.Add(s); 
    }
}

如果您不想担心采用相反的方向,则不需要降序布尔值。

于 2013-04-09T14:00:16.617 回答