[英]How to Shuffle Items in a ListView C#?
I am making a very simple MP3, WAV, and WMA media player.我正在制作一个非常简单的 MP3、WAV 和 WMA 媒体播放器。
The music files are listed within a listView consisting of two columns (Column 1: Audio Title, Column 2: File Location).音乐文件列在由两列(第 1 列:音频标题,第 2 列:文件位置)组成的列表视图中。
I would like to create a button that will shuffle and randomize ALL of the items that are in the list view.我想创建一个按钮来随机排列列表视图中的所有项目。
Here's an example:下面是一个例子:
Title Location
SONG1 C:\\A LOCATION
SONG2 "
SONG3 "
SONG4 "
SONG5 "
SONG6 "
into this:进入这个:
Title Location
SONG6 C:\\A LOCATION
SONG3 "
SONG4 "
SONG2 "
SONG1 "
SONG5 "
I'm using axMediaPlayer (.wmp)我正在使用 axMediaPlayer (.wmp)
Thank you for the help!谢谢你的帮助! :) :)
Random rnd = new Random();
var randomizedList = from item in listbox.Items
orderby rnd.Next()
select item;
Then assign the randomizedList back to the listbox然后将 randomlist 分配回列表框
or或
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
Usage:用法:
var products = listview.Items.ToList();
products.Shuffle();
using System;
using System.Collections;
using System.Windows.Forms;
public static class ListViewExtensions
{
public static void Randomize(this ListView lv)
{
ListView.ListViewItemCollection list = lv.Items;
Random rng = new Random();
int n = list.Count;
lv.BeginUpdate();
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
ListViewItem value1 = (ListViewItem)list[k];
ListViewItem value2 = (ListViewItem)list[n];
list[k] = new ListViewItem();
list[n] = new ListViewItem();
list[k] = value2;
list[n] = value1;
}
lv.EndUpdate();
lv.Invalidate();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.