I have a list of data without duplicates. In this example, I will say that my list
List<string> list1 = new List<string>() { "A", "B", "C", "D" };
I want to perform my operation on each element in the list with respect to all other elements in the list, except when I already performed my operation on them (AB and BA), or if they are the same (AA).
EG.
A against B A against C A against D B against C B against D C against D
Now it’s pretty easy to do, but my list is very long, and this process can be quite time-consuming. Also with the data that I have, I don’t need to start the data matching operation or if the operation is already completed
EG.
A against A - Skip A against B - Good A against C - Good A against D - Good B against A - Skip (we already did A against B) B against B - Skip B against C - Good B against D - Good C against A - Skip
etc.
What I was looking for (and I don’t even know if it exists) is a simple method that I can use for this, instead of disconnecting the two loops and doing my work and saving the results for comparison with later ones.
Listing through a list of O(n*n) , but since I do not need to compare more than half of the results, this is a waste of time, since I know that I only need to check O(n*(n/2))
The code I use is as follows
List<string> list1 = new List<string>() { "A", "B", "C", "D" }; List<string> list2 = new List<string>(list1); List<string> listResult = new List<string>(); list2.Reverse(); int i = 0; foreach (var a in list1) { for (int j = 0; j < (list2.Count / 2); j++) { i++; Console.WriteLine("Looped {0} times", i);
The above code works fine (I will need to edit list2.Count / 2 part to account for the odd list).
Is there a better way to do this? LINQ extension method that I missed? My problem is that I really don't know what for Google.
I wondered if there was a method that would return a list containing only those elements that I would like to then loop through and complete my operation. Maybe something uses .SelectMany()