Loop through list of strings to find different values

Viewed 71

I have a list that is populated with different values:

e.g

{GBP, GBP, GBP, USD} 

so far I have this:

List<string> currencyTypes = new List<string>();

for (int i = 0; i < currencyTypes.Count; i++)
{
    if currencyTypes[i] != [i]
        console.writeline("currencies are different");
}

So if the list has all the same entries, the if statement shouldnt fire

e,g {GBP, GBP, GBP, GBP}

however if any of the values are different from the rest then the if statement should notice the difference and fire.

this doesnt work however.

any ideas?

3 Answers

First of all, your list is empty. Maybe it's for the sake of the example. If not, initialize it with data. However, modify line 3 and 5 to this to fix the problem.

for (int i = 1; i < currencyTypes.Count; i++)
{
    if (currencyTypes[i] != currencyTypes[i-1])
   .... 
 } 

You could use LINQ to test whether all entries are the same

if (currencyTypes.Distinct().Count() > 1) {
    Console.WriteLine("currencies are different");
}

Slightly more efficient for long lists:

if (currencyTypes.Count > 1 && currencyTypes.Distinct().Skip(1).Any()) {
    Console.WriteLine("currencies are different");
}

This is more efficient because Any iterates at most one element unlike Count which iterates the whole list.

you should first group your data and find your result depending the group.

eg

    List<string> currencyTypes = new List<string>() {"USD", "GBP", "GBP", "GBP" };

    // group list items
    var typeGroup = currencyTypes.GroupBy(t => t);
    
    if (typeGroup.Count() > 1)
        Console.WriteLine("currencies are different");
    // .    
    // .
    
    // also you can check what item is unique   
    foreach (var t in typeGroup.Where(g => g.Count() == 1 ))
    {
        Console.WriteLine($"{t.Single()} is different");
    }
Related