I have 2 foreach
nested items class, in which I go through two lists, and if the element of list 1 is found in list 2, it must do a couple of operations, the dilemma is that when dealing with very long lists, it takes a lot and I need to improve that time.
Code:
foreach (Articulo x in Articulos) //Lista Principal
{
foreach(Articulo y in listSec)
{
if (y.Art_CodGen == x.Art_CodGen) //Si son Iguales
{
if (y.Precios[0] != x.Precios[i]) //Y tienen distinto precio
{
updatedRows += UpdateArticulo(x, i); // Actualizo
}
}
}
}
If you want to improve performance you can use
Thread
orForEach
async to loop through them faster. One way to implement this behavior would be with the functionParallel.ForEach<TSource>(IEnumerable<TSource> source, Action<TSource> body);
Also in the second search you could use
Linq
to only search for the ones you need to go through (although after all it is a search but more optimized).An example of the implementation of this solution would be something like this:
The detail that I see in your code is that for each item in list 1 you are going through list 2 completely, because what your if does is identify that they are the same in the Art_CodGen and that they are of different prices, to finally update, this it doesn't stop the foreach of list 2 and keeps iterating objects as well as still evaluating and affecting the performance of the application. I will leave you the code fragment that I use in these cases and I will explain it to you in detail below:
Now I will explain the scenario that I set up, I have defined a person type object with two attributes, you know to simplify things:
Two person-type lists are created:
Objects are added to the lists where, mind you, three of the people will be on both lists (
Katz , Manuel y Uriel
).The scenario is already defined, now if I explain the code to you, a single foreach is performed that goes through the person type objects in the first list, within the foreach of the first list an auxiliary person object is created, now this is the part where you must provide attention:
A search is performed using the function
FirstOrDegault
and a lambda expression (very useful) where it is evaluated that the code (ID) of the pItem object of list 1 is found in list two:if it finds someone like it in list 2, the perAux object will not be null and well, you can also do your other if (the one with the prices), because the perAux object is the one you extracted from list 2 and the pItem is the one from the list 1 that is, you have the two objects to do the logic you require .
This is the output of the program.
You can apply binary search. I'll explain the idea:
Advantage:
You always divide the set and choose the set in which your object can surely be.
Example:
5
{12,5, 1 , 4, 49, 89}
5 {1,4,5,12,49,89}
5 {1,4,5}{12,49,89}
this in the 1st subset, 49 is the first element of the second set, and 49 is greater than 5 so 5 is not in the second subset.
second iteration {1,4,5}