HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Searching item in array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemarraysearching

Problem

I have a program that calculates some values and saves them to an array. Before save a value, program checks if there is already an identical value in array:

string someData = GetData();
 bool newItem = true;
 int arrayDataLength = arrayData.Length;
 for (int x = 0; x < arrayDataLength; x++)
 {
     if (arrayData[x] == someData)
     {
         newItem = false;
         arrayDataCount[x]++;
         break;
     }
  }
  if (newItem == true)
  {
       Array.Resize(ref arrayData, (arrayDataLength + 1));
       Array.Resize(ref arrayDataCount, (arrayDataLength + 1));
       arrayData[arrayDataLength] = someData;
       arrayDataCount[arrayDataLength]++;
  }


Sometimes arrays with data become big, and program works a bit slow.
How can I optimize perfomance of this action?

Solution

If you don't need to count the number of occurences, use a Set:

private readonly ISet data = new HashSet();

public void AddNewData()
{
    string someData = GetData();
    data.Add(someData);
}


If you need to count the occurences, you should use a Dictionary:

private readonly IDictionary data = new Dictionary();

public void AddNewData()
{
    string someData = GetData();
    if (data.ContainsKey(someData))
    {
        data[someData]++;
    }
    else
    {
        data[someData] = 1;
    }
}


Alternatively, you could just use a List and calculate the counts when you need them, using the LINQ GroupBy extension method:

private readonly ICollection data = new List();

public void AddNewData()
{
    string someData = GetData();
    data.Add(someData); // data might contain duplicates
}

public void PrintData() // use LINQ to count number of occurences
{
    foreach (var entry in data.GroupBy(x => x))
    {
        Console.WriteLine("{0} {1}", entry.Key, entry.Count());
    }
}

Code Snippets

private readonly ISet<string> data = new HashSet<string>();

public void AddNewData()
{
    string someData = GetData();
    data.Add(someData);
}
private readonly IDictionary<string, int> data = new Dictionary<string, int>();

public void AddNewData()
{
    string someData = GetData();
    if (data.ContainsKey(someData))
    {
        data[someData]++;
    }
    else
    {
        data[someData] = 1;
    }
}
private readonly ICollection<string> data = new List<string>();

public void AddNewData()
{
    string someData = GetData();
    data.Add(someData); // data might contain duplicates
}

public void PrintData() // use LINQ to count number of occurences
{
    foreach (var entry in data.GroupBy(x => x))
    {
        Console.WriteLine("{0} {1}", entry.Key, entry.Count());
    }
}

Context

StackExchange Code Review Q#20574, answer score: 4

Revisions (0)

No revisions yet.