This response has been on the site since 5/21/2014 . This question is actually the duplicate duplicate . As it remained open and was answered, I will respond as well.
Note that I did not change the solution (here I took the part that improved the method to choose which data range you want, but does not change the execution itself), which is the important thing. I just took the strings part from the example. If the problem is not knowing how to add elements from the array , then the question should be this.
using System;
using System.Collections.Generic;
public static class Sorteio {
public static void Main() {
int[] array = { 1, 2, 3, 4 };
array.Shuffle();
foreach (var valor in array) {
Console.WriteLine(valor);
}
Console.WriteLine("Soma: {0}", array[0] + array[2]); // soma 1o. e 3o. elemento
//vamos de novo
array.Shuffle(); //com poucos númros tem chance de repetir
Console.WriteLine("Soma novo sorteio: {0}", array[0] + array[2]);
}
}
namespace System.Collections.Generic {
public static class IListExt {
static Random r = new Random(DateTime.Now.Millisecond);
public static void Shuffle<T>(this IList<T> list) {
upperItem = list.Count;
lowerItem = 0;
for (int i = lowerItem; i < upperItem; i++) {
int j = r.Next(i, upperItem);
T tmp = list[j];
list[j] = list[i];
list[i] = tmp;
}
}
public static void Shuffle<T>(this IList<T> list, int upperItem) {
list.Shuffle(0, upperItem);
}
public static void Shuffle<T>(this IList<T> list) {
list.Shuffle(0, list.Count);
}
}
}
See running on dotNetFiddle .
To assign to a variable just do this:
var soma = array[0] + array[2]; //listas começam em zero então o elemento sempre é -1 ao desejado
For more details, see the answers already there in the original question.