Home > Enterprise >  C# - How do I prevent duplicate results in nested loop?
C# - How do I prevent duplicate results in nested loop?

Time:12-01

This is part of my code, I want to add to finalSorted the two values from arrFinal that share the same url (this is what I get with the Split as line[5] and zLine[5]), and I want them to be one above the other. I try to compare if they are not exactly the same entry by comparing line[1] and zLine[1] that stores a REQUEST or RESPONSE. But this part is problematic too, because it returns the same result, not the one with line[1] different than zLine[1].

The problem is that I want to compare each iteration of the first loop with all other iterations (second for loop) to check if they match and return, one above the other, the two that have the same url but different field for RESPONSE and REQUEST.

List<string> finalSorted = new List<string>();
    
for (int i = 0;i < arrFinal.Count; i  )
{
    string[] line = arrFinal[i].Split(";");
    for (int z = 0; z < arrFinal.Count; z  )
    {
        string[] zLine = arrFinal[z].Split(";");
        if (line[5] == zLine[5] && line[1] != zLine[1])
        {
            finalSorted.Add(arrFinal[i]);
            finalSorted.Add(arrFinal[z]);
        }
        else
        {
            continue;
        }
    }
}

Any help or advice would be appreciated, I'm open to even change entirely the idea for implementing this solution.

Thank you in advance!

Edit:

This is what I get:

00:00:00.7443;REQUEST;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7793;RESPONSE;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7793;RESPONSE;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7443;REQUEST;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962

This is what I want:

00:00:00.7443;REQUEST;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7793;RESPONSE;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962

CodePudding user response:

// i assume this format in arrFinal
var arrFinal = new string[] { 
    "v0;REQUEST;v2;v3;v4;url",
    "v0;RESPONSE;v2;v3;v4;url",
};

// order by "url" then by "REQUEST or RESPONSE"
var sorted = arrFinal.Distinct().OrderBy(x => {
    // TODO, range check etc...
    var urlPart = x.Split(';')[5];
    return urlPart;
}).ThenBy(x => {
    var requestOrResponse = x.Split(';')[1];
    return requestOrResponse;
}).ToList();
  • Related