How to sort words from an array without repeating them? [duplicate]

1

I'm doing a college project where I need to simulate the library, so I have an array with the name of 20 teams and I need to raffle 10 teams but not repeat any of them and present those teams in a ListBox , however I'm not getting it, could you give me suggestions on how to create this method of drawing?

And if possible, some way to add the values of a CheckBox to an array to make a comparison with the teams drawn.

My array :

public String[] times =
          {
                "Corinthians"
                ,"Palmeiras"
                ,"Santos"
                ,"Grêmio"
                ,"Cruzeiro"
                ,"Botafogo"
                ,"Flamengo"
                ,"Vasco da Gama"
                ,"Atlético-PR"
                ,"Atlético"
                ,"São Paulo"
                ,"Chapecoense"
                ,"Bahia"
                ,"Fluminense"
                ,"Sport Recife"
                ,"Coritiba"
                ,"Ponte Preta"
                ,"Avaí"
                ,"EC Vitória"
             };
    
asked by anonymous 20.11.2017 / 05:58

1 answer

2

First declare a Random

Random rnd = new Random();

Make random get a value in the middle of the array by random generated in index

int r = rnd.Next(times.Length);

Now you can get your team:

var timesorteado = ((string)times[r]);

Then generate a list and add .. and filter not to add duplicate

I made a simple example in a console application, but it can be improved .. but just to give you an idea of the logic, do not forget to using System.Linq; and System.Collections.Generic;

private static void Main(string[] args)
{
    String[] times =
    {
        "Corinthians", "Palmeiras", "Santos", "Grêmio", "Cruzeiro", "Botafogo", "Flamengo", "Vasco da Gama",
        "Atlético-PR", "Atlético", "São Paulo", "Chapecoense", "Bahia", "Fluminense", "Sport Recife",
        "Coritiba", "Ponte Preta", "Avaí", "EC Vitória"
    };

    var lstTimesSorteados = new List<string>();

    for (var i = 0; i < 10; i++)
    {
        var timesorteado = Sorteio(times);

        if (!lstTimesSorteados.Any(x => x.Contains(timesorteado)))
        {
            lstTimesSorteados.Add(timesorteado);
        }
        else
        {
            i--;
        }
    }
}

private static string Sorteio(string[] times)
{
    var rnd = new Random();

    var r = rnd.Next(times.Length);
    return ((string)times[r]);
}

Then it's simple, just compare your checkbox with lstTimesShorts .

    
20.11.2017 / 09:09