There are extension methods Count() and ElementAt(int) declared on IEnumerable<T> . They are declared in the System.Linq namespace, which should be included by default in your .cs files if you use any version of C # later than C # 3. This means that you could just do:
for (int i = 0; i < myList.Count() - 1; ++i) { for (int j = i+1; j < myList.Count(); ++j) { DoMyStuff(myList.ElementAt(i), myList.ElementAt(j)); } }
However, note that these are methods and will be called again and again during the iteration, so you can save their result in variables, for example:
var elementCount = myList.Count(); for (int i = 0; i < elementCount - 1; ++i) { var iElement = myList.ElementAt(i); for (int j = i+1; j < elementCount; ++j) { DoMyStuff(iElement, myList.ElementAt(j)); } }
You can also try LINQ, which will select all pairs of matching elements, and then use a simple foreach to invoke processing, for example:
var result = myList.SelectMany((avalue, aindex) => myList.Where((bvalue, bindex) => aindex < bindex) .Select(bvalue => new {First = avalue, Second = bvalue})); foreach (var item in result) { DoMyStuff(item.First, item.Second); }
Sweko source share