dros
dros

Reputation: 1557

Loop through list of strings to find different values

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?

Upvotes: 2

Views: 326

Answers (3)

AliReza Sabouri
AliReza Sabouri

Reputation: 5215

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");
    }

Upvotes: 0

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112392

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.

Upvotes: 1

Qudus
Qudus

Reputation: 1520

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])
   .... 
 } 

Upvotes: 1

Related Questions