您可以隨機播放一次,然後剝離蘋果和桔子
這將是一個多一點效率比隨機對每個水果,但短名單上不會有太大的區別
public static void TestFruit()
{
List<Fruit> fruits = new List<Fruit>();
fruits.Add(new Fruit("01", "orange")); fruits.Add(new Fruit("02", "orange"));
fruits.Add(new Fruit("03", "orange")); fruits.Add(new Fruit("04", "orange"));
fruits.Add(new Fruit("05", "orange")); fruits.Add(new Fruit("06", "orange"));
fruits.Add(new Fruit("07", "orange")); fruits.Add(new Fruit("08", "orange"));
fruits.Add(new Fruit("09", "orange")); fruits.Add(new Fruit("10", "orange"));
fruits.Add(new Fruit("01", "apple")); fruits.Add(new Fruit("02", "apple"));
fruits.Add(new Fruit("03", "apple")); fruits.Add(new Fruit("04", "apple"));
fruits.Add(new Fruit("05", "apple")); fruits.Add(new Fruit("06", "apple"));
fruits.Add(new Fruit("07", "apple")); fruits.Add(new Fruit("08", "apple"));
fruits.Add(new Fruit("09", "apple")); fruits.Add(new Fruit("10", "apple"));
fruits.Add(new Fruit("11", "apple")); fruits.Add(new Fruit("12", "apple"));
fruits.Add(new Fruit("13", "apple")); fruits.Add(new Fruit("14", "apple"));
fruits.Add(new Fruit("15", "apple")); fruits.Add(new Fruit("16", "apple"));
fruits.Add(new Fruit("17", "apple")); fruits.Add(new Fruit("18", "apple"));
fruits.Add(new Fruit("19", "apple")); fruits.Add(new Fruit("20", "apple"));
Shuffle<Fruit>(fruits);
List<Fruit> randomFruits = fruits.Where(x => x.Type == "apple").Take(7).ToList();
randomFruits.AddRange(fruits.Where(x => x.Type == "orange").Take(3));
foreach (Fruit f in randomFruits)
{
Debug.WriteLine("Name {0} Type {1}", f.Name, f.Type);
}
Debug.WriteLine("");
}
public static void Shuffle<T>(List<T> list)
{ // FisherYates
for (int i = list.Count - 1; i >= 1; i--)
{
int j = rand.Next(i + 1);
if (j != i)
{ // exchange values
T curVal = list[i];
list[i] = list[j];
list[j] = curVal;
}
}
}
public class Fruit
{
public string Name { get; set; }
public string Type { get; set; }
public Fruit(string name, string type)
{
Name = name;
Type = type;
}
}
爲什麼3個橙子7個蘋果具體? – Abion47