[英]How to Shuffle Items in a ListView C#?
我正在制作一個非常簡單的 MP3、WAV 和 WMA 媒體播放器。
音樂文件列在由兩列(第 1 列:音頻標題,第 2 列:文件位置)組成的列表視圖中。
我想創建一個按鈕來隨機排列列表視圖中的所有項目。
下面是一個例子:
Title Location
SONG1 C:\\A LOCATION
SONG2 "
SONG3 "
SONG4 "
SONG5 "
SONG6 "
進入這個:
Title Location
SONG6 C:\\A LOCATION
SONG3 "
SONG4 "
SONG2 "
SONG1 "
SONG5 "
我正在使用 axMediaPlayer (.wmp)
謝謝你的幫助! :)
Random rnd = new Random();
var randomizedList = from item in listbox.Items
orderby rnd.Next()
select item;
然后將 randomlist 分配回列表框
或
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;
}
}
用法:
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.