John
John

Reputation: 217

Looping through 2 arrays to compare values c#

I've looked around and can't really find the specific answer to this problem I have. I have two arrays, one that holds a list of people and another that holds a Person object with a name property. I'm trying to loop through the array of objects and if the value in the .Name of the person equals the corresponding value in the array of strings, then I add 1 to a counter. I've seen answers given using Linq, but i'm not really familiar with that. Is there a basic way to do this that i'm overlooking or will I need to use Linq. Thanks in advance. Here's the code I have.

int count = 0;

string[] names = new string[]{"John","Jim","Mary","Joan","Tim"};

ObservableCollection<Person> people = (ObservableCollection<Person>)Session["People"];

foreach (var pe in people)
{
    for (int i = 0; i < names.Length; i++)
    {
        if (pe.Name == names[i])
            count++;
    }    
}

Upvotes: 0

Views: 1417

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

You should use HashSet<string> to store names. It has O(1) Contains method, when the same Contains method on string[] is O(n).

var set = new HashSet<string>(names);

And then

foreach (var pe in people)
{
    if(set.Contains(pe.Name))
        count++;  
}

or with LINQ

count = people.Count(person => set.Contains(person.Name));

It will make your solution O(m) instead of O(n*m)

Upvotes: 4

Ben Aaronson
Ben Aaronson

Reputation: 6975

What you've posted will work. A simpler version of the loop would be:

foreach (var pe in people)
{
    if(names.Contains(pe.Name))
        count++;  
}

Using LINQ, it's a one line affair:

count = people.Count(person => names.Contains(person.Name));

I'd strong recommend taking this opportunity to become familiar with LINQ. It's very powerful and in situations like this results in code that's both more concise and more readable.

Upvotes: 1

alexmac
alexmac

Reputation: 19607

Try this solution:

var count = people.Count(pe => names.Contains(pe.Name));

Upvotes: 2

Related Questions