0

I have a list of 40 names, a list of 40 picture boxes, I want to show these names randomly and uniquely in picture boxes.

I tried but my effort is worthless. Any help would be appriciated.

        Random r = new Random();

        List<int> list = Enumerable.Range(1, box.Count).ToList();
        List<int> rndList = new List<int>();
        Random rnd = new Random();
        int no = 0;
        for (int i = 0; i < box.Count; i++)
        {
            no = rnd.Next(0, list.Count);
            rndList.Insert(i, no);
            list.Remove(no);
        }

        for (int i = 0; i < box.Count; i++)
        {
            System.Reflection.Assembly sysrefass = System.Reflection.Assembly.GetExecutingAssembly();
            var rm = new System.Resources.ResourceManager(sysrefass.GetName().Name + ".Properties.Resources", ((System.Reflection.Assembly)sysrefass));
            box[i].Image = (Image)rm.GetObject(rndList[i].ToString());

        }
User_khan
  • 25
  • 5
  • You don't actually want random items, what you want to do is shuffle the list of items. There are many examples of that on this site you can use – Scott Chamberlain Jul 01 '16 at 21:02

1 Answers1

-1

Just fill box[] in ordinal order, for example with

box[i].Image = (Image)rm.GetObject(i.ToString());

and then use OrderBy() with random value or Guid:

var randomizedBox = box.OrderBy(b => rnd.Next).ToArray();
var randomizedBox2 = box.OrderBy(b => Guid.NewGuid()).ToArray();
Vadim Martynov
  • 8,602
  • 5
  • 31
  • 43
  • I don't understand where I have to put 2nd statement you wrote here. – User_khan Jul 01 '16 at 21:01
  • This is not a [good idea](http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm) – Hamid Pourjam Jul 01 '16 at 21:02
  • Well you can use it immediately after last loop. Also, you can reuse same variable like `box = box.OrderBy(b => rnd.Next).ToArray();` but it can be unclear because name `box` does not contain extra information about your variable. You should put this line after filling box array. – Vadim Martynov Jul 01 '16 at 21:03
  • @dotctor well Scott not referenced concrete answer about shuffling but the first google link uses the same method: http://stackoverflow.com/questions/108819/best-way-to-randomize-an-array-with-net and wow it has good rating because it's short and useful. John's article is good, but my solution is not bad too I think. – Vadim Martynov Jul 01 '16 at 21:45