Collections
Search and Count
A loop can count how many collection items match a target.
Search and Count
SearchCount.cs
using System;
class Program
{
static void Main()
{
string target = ;
string[] labels = { "red", "blue", "red", "gold" };
int matches = 0;
foreach (string label in labels)
{
if (label == target)
{
matches++;
}
}
Console.WriteLine($"target={target}");
Console.WriteLine($"matches={matches}");
}
}
using System;
class Program
{
static void Main()
{
string target = ;
string[] labels = { "red", "blue", "red", "gold" };
int matches = 0;
foreach (string label in labels)
{
if (label == target)
{
matches++;
}
}
Console.WriteLine($"target={target}");
Console.WriteLine($"matches={matches}");
}
}
using System;
class Program
{
static void Main()
{
string target = ;
string[] labels = { "red", "blue", "red", "gold" };
int matches = 0;
foreach (string label in labels)
{
if (label == target)
{
matches++;
}
}
Console.WriteLine($"target={target}");
Console.WriteLine($"matches={matches}");
}
}
search
A search checks each item until it finds or counts matches.