Если Вам по каким-либо причинам нужно случайным образом перемешать элементы списка List, то мы видимо, что специальной встроенной функции в C# для этих целей не предусмотрено, но унывать не стоит, всегда можно легко получить желаемое, причем даже ни одним способом.
Итак, у нас есть список из нескольких целых чисел и нужно перемешать их случайным образом.
Способ 1.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class ProgramMain
{
static void Main(string[] args)
{
Random rnd = new Random();
List<int> lst = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < lst.Count; i++)
{
int tmp = lst[i];
lst.RemoveAt(i);
lst.Insert(rnd.Next(lst.Count), tmp);
}
foreach(int i in lst)
Console.Write( i + " ");
Console.ReadLine();
}
}
}
Итак, у нас есть список из нескольких целых чисел и нужно перемешать их случайным образом.
Способ 1.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class ProgramMain
{
static void Main(string[] args)
{
Random rnd = new Random();
List<int> lst = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < lst.Count; i++)
{
int tmp = lst[i];
lst.RemoveAt(i);
lst.Insert(rnd.Next(lst.Count), tmp);
}
foreach(int i in lst)
Console.Write( i + " ");
Console.ReadLine();
}
}
}
Способ 2.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class ProgramMain
{
static void Main(string[] args)
{
Random rnd = new Random();
List<int> lst = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int n = lst.Count;
while (n > 1)
{
n--;
int k = rnd.Next(n + 1);
int value = lst[k];
lst[k] = lst[n];
lst[n] = value;
}
foreach(int i in lst)
Console.Write( i + " ");
Console.ReadLine();
}
}
}
Способ 3.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class ProgramMain
{
static void Main(string[] args)
{
Random rnd = new Random();
List<int> lst = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int z = 0;
List<int> lst2 = new List<int>();
while (lst.Count > 1)
{
z = rnd.Next(lst.Count);
lst2.Add(lst[z]);
lst.RemoveAt(z);
}
lst2.Add(lst[rnd.Next(0)]);
foreach(int i in lst2)
Console.Write( i + " ");
Console.ReadLine();
}
}
}
Способ 4.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class ProgramMain
{
static void Main(string[] args)
{
Random rnd = new Random();
List<int> lst = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
SortedList<int, int> newList = new SortedList<int, int>();
foreach (int item in lst)
{
newList.Add(rnd.Next(), item);
}
lst.Clear();
for (int i = 0; i < newList.Count; i++)
{
lst.Add(newList.Values[i]);
}
foreach(int i in lst)
Console.Write( i + " ");
Console.ReadLine();
}
}
}
Способ 5.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class ProgramMain
{
static void Main(string[] args)
{
Random rnd = new Random();
List<int> lst = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> lst2 = lst.OrderBy(x=>rnd.Next()).ToList();
foreach(int i in lst)
Console.Write( i + " ");
Console.ReadLine();
}
}
}
Сегодня у меня получилось пять способов рандомного перебора элементов списка, все они достаточно просты и могут быть применены и для пользовательских списков. Что касается четвертого способа, который выглядит более объемным, то в нем создается изначально отсортированный список, который затем рандомно переносится в исходный.
Последний способ является самым компактным и красивым, но его не всегда целесообразно применять.
Благодарю!
ОтветитьУдалить