Programing

목록에서 임의의 항목에 액세스하는 방법?

lottogame 2020. 4. 27. 07:54
반응형

목록에서 임의의 항목에 액세스하는 방법?


ArrayList가 있고 버튼을 클릭 한 다음 해당 목록에서 문자열을 임의로 골라서 메시지 상자에 표시 할 수 있어야합니다.

어떻게하면 되나요?


  1. Random어딘가에 클래스 의 인스턴스를 만듭니다 . 난수가 필요할 때마다 새 인스턴스를 만들지 않는 것이 중요합니다. 생성 된 수에서 균일 성을 얻으려면 이전 인스턴스를 재사용해야합니다. static어딘가에 필드가있을 수 있습니다 (스레드 안전 문제에주의).

    static Random rnd = new Random();
    
  2. Random인스턴스에 다음의 최대 항목 수를 가진 임의의 숫자를 제공하도록 요청하십시오 ArrayList.

    int r = rnd.Next(list.Count);
    
  3. 문자열을 표시하십시오.

    MessageBox.Show((string)list[r]);
    

나는 보통이 작은 확장 메소드 모음을 사용한다 :

public static class EnumerableExtension
{
    public static T PickRandom<T>(this IEnumerable<T> source)
    {
        return source.PickRandom(1).Single();
    }

    public static IEnumerable<T> PickRandom<T>(this IEnumerable<T> source, int count)
    {
        return source.Shuffle().Take(count);
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.OrderBy(x => Guid.NewGuid());
    }
}

강력한 형식의 목록의 경우 다음과 같이 쓸 수 있습니다.

var strings = new List<string>();
var randomString = strings.PickRandom();

당신이 가진 모든 것이 ArrayList라면, 당신은 그것을 캐스팅 할 수 있습니다 :

var strings = myArrayList.Cast<string>();

넌 할 수있어:

list.OrderBy(x => Guid.NewGuid()).FirstOrDefault()

Random인스턴스를 만듭니다 .

Random rnd = new Random();

임의의 문자열을 가져옵니다.

string s = arraylist[rnd.Next(arraylist.Count)];

그러나이 작업을 자주 수행하면 Random객체를 재사용해야 합니다. 클래스에서 정적 필드로 넣어 한 번만 초기화 한 다음 액세스하십시오.


또는 다음과 같은 간단한 확장 클래스 :

public static class CollectionExtension
{
    private static Random rng = new Random();

    public static T RandomElement<T>(this IList<T> list)
    {
        return list[rng.Next(list.Count)];
    }

    public static T RandomElement<T>(this T[] array)
    {
        return array[rng.Next(array.Length)];
    }
}

그런 다음 전화하십시오.

myList.RandomElement();

배열에서도 작동합니다.

OrderBy()더 큰 컬렉션에는 비용이 많이들 수 있으므로 전화 피할 수 있습니다. List<T>이를 위해 인덱스 모음 또는 배열을 사용하십시오 .


왜 안되 겠어요 :

public static T GetRandom<T>(this IEnumerable<T> list)
{
   return list.ElementAt(new Random(DateTime.Now.Millisecond).Next(list.Count()));
}

ArrayList ar = new ArrayList();
        ar.Add(1);
        ar.Add(5);
        ar.Add(25);
        ar.Add(37);
        ar.Add(6);
        ar.Add(11);
        ar.Add(35);
        Random r = new Random();
        int index = r.Next(0,ar.Count-1);
        MessageBox.Show(ar[index].ToString());

이 ExtensionMethod를 한동안 사용했습니다.

public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int count)
{
    if (count <= 0)
      yield break;
    var r = new Random();
    int limit = (count * 10);
    foreach (var item in list.OrderBy(x => r.Next(0, limit)).Take(count))
      yield return item;
}

단 하나가 아닌 더 많은 아이템이 필요했습니다. 그래서 나는 이것을 썼다.

public static TList GetSelectedRandom<TList>(this TList list, int count)
       where TList : IList, new()
{
    var r = new Random();
    var rList = new TList();
    while (count > 0 && list.Count > 0)
    {
        var n = r.Next(0, list.Count);
        var e = list[n];
        rList.Add(e);
        list.RemoveAt(n);
        count--;
    }

    return rList;
}

이를 통해 다음과 같이 원하는만큼 요소를 얻을 수 있습니다.

var _allItems = new List<TModel>()
{
    // ...
    // ...
    // ...
}

var randomItemList = _allItems.GetSelectedRandom(10); 

왜 안됩니까 [2] :

public static T GetRandom<T>(this List<T> list)
{
     return list[(int)(DateTime.Now.Ticks%list.Count)];
}

참고 URL : https://stackoverflow.com/questions/2019417/how-to-access-random-item-in-list

반응형