sourcecode

목록에서 임의 항목에 액세스하는 방법은 무엇입니까?

copyscript 2023. 5. 24. 22:20
반응형

목록에서 임의 항목에 액세스하는 방법은 무엇입니까?

저는 배열 목록을 가지고 있습니다. 버튼을 클릭한 다음 목록에서 문자열을 무작위로 선택하여 메시지 상자에 표시할 수 있어야 합니다.

제가 이걸 어떻게 해야 할까요?

  1. 다음의 인스턴스를 만듭니다.Random어디선가 수업을 해요.난수가 필요할 때마다 새 인스턴스를 만들지 않는 것이 매우 중요합니다.이전 인스턴스를 재사용하여 생성된 수를 균일하게 만들어야 합니다.당신은 가질 수 있습니다.static필드 어딘가(스레드 안전 문제에 주의):

    static Random rnd = new Random();
    
  2. 질문합니다.Random인스턴스(instance)는 항목의 최대 수와 함께 임의의 수를 제공합니다.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();

배열 목록만 있으면 다음과 같이 캐스트할 수 있습니다.

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

할 수 있는 일:

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

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

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>또는 이 목적을 위한 배열입니다.

작성Random인스턴스:

Random rnd = new Random();

임의 문자열 가져오기:

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

하지만, 만약 당신이 이것을 자주 한다면, 당신은 그것을 다시 사용해야 한다는 것을 기억하세요.Random물건.클래스에서 정적 필드로 설정하여 한 번만 초기화된 다음 액세스합니다.

목록 내 항목의 순서가 추출 시 중요하지 않은 경우(그리고 각 항목을 한 번만 선택해야 함) 대신 스레드 안전하고 순서가 지정되지 않은 개체 모음인 를 사용할 수 있습니다.

var bag = new ConcurrentBag<string>();
bag.Add("Foo");
bag.Add("Boo");
bag.Add("Zoo");

이벤트 처리기:

string result;
if (bag.TryTake(out result))
{
    MessageBox.Show(result);
}

는 순서가 지정되지 않은 컬렉션에서 "임의" 개체를 추출하려고 시도합니다.

그렇지 않은 이유:

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());

나는 이 확장 방법을 한동안 사용해 왔습니다.

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); 

JSON 파일에서 국가 이름을 임의로 인쇄하고 있습니다.
모델:

public class Country
    {
        public string Name { get; set; }
        public string Code { get; set; }
    }

구현:

string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\..\")) + @"Data\Country.json";
            string _countryJson = File.ReadAllText(filePath);
            var _country = JsonConvert.DeserializeObject<List<Country>>(_countryJson);


            int index = random.Next(_country.Count);
            Console.WriteLine(_country[index].Name);

그렇지 않은 이유 [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

반응형