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.

6
  • 6
    array.count(x=>x==item)==2 Commented Jul 28, 2014 at 14:25
  • 2
    Or array.Distinct() and comparing this length vs original will check for all entries Commented Jul 28, 2014 at 14:27
  • @Sayse That will return if any item is repeated, not for the particular item. Commented Jul 28, 2014 at 14:28
  • @SriramSakthivel - The first sentence is slightly ambiguous which is why I built upon Mohammads comment Commented Jul 28, 2014 at 14:29
  • @Selman22 I strongly suspect is this a duplicate of the related thread? Find some other question please, or reopen it. Commented Jul 28, 2014 at 14:31

1 Answer 1

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.