0

i want to check if a string array includes a string more than one time.

for example

string[] array = new string[]{"A1","A2","A3"};
string item = "A1";

look for item in array, include item just once return false

string[] array = new string[]{"A1","A2","A3","A1"};
string item = "A1";

return true

Any insight would be greatly appreciated.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
user3868224
  • 363
  • 1
  • 6
  • 19

1 Answers1

2

If you want to know whether or not a particular item is repeated more than once, you can get the count of the item and check if it is bigger than 1:

bool isRepeated = array.Count(x => x == item) > 1;

Or, you can do it more efficiently with a HashSet:

bool isRepeated = false;
var set = new HashSet<int>();
foreach(var x in array)
{
    if(x == item && !set.Add(x)) 
    {
       isRepeated = true; 
       break;
    }
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184