1

i want to check if the user inputs a same string twice using array. don't have any idea on what codes to use can you suggest anything?

if the user inputs "1A" twice i want to print "Already Taken", and if the user enter a string which is not in my Array(arr) i want to print "invalid input"

this is my array

      string[,] arr = new string[,]
        {
            {"1A","2A","3A","4A","5A"},
            {"1B","2B","3B","4B","5B"},
            {"1C","2C","3C","4C","5C"},
            {"1D","2D","3D","4D","5D"},
        };
5
  • linq will be a good start Commented Oct 13, 2014 at 12:30
  • You'll have to give some sample input/output, the question is not very clear Commented Oct 13, 2014 at 12:31
  • 2
    @DorCohen that really doesn't sound like a LINQ question; I genuinely have no clue what the OP is trying to do, but I'm still pretty confident that LINQ isn't the first tool to pick up Commented Oct 13, 2014 at 12:32
  • @Josh you haven't given us any context as to how the array relates to the user's input... is the question here "the user must select two different values that are in the array"?. Or is it "the array represents the user's input; the values must be distinct"? Commented Oct 13, 2014 at 12:33
  • @MarcGravell take a look on my answer, I think that's what he meant Commented Oct 13, 2014 at 12:34

4 Answers 4

3

You can use a HashSet<string> to check if there are duplicates:

var set = new HashSet<string>();
bool noDuplicate = arr.Cast<string>().All(set.Add);
Sign up to request clarification or add additional context in comments.

1 Comment

very tidy implementation
2

You can use Set, e.g. HashSet<String>:

  HashSet<String> hs = new HashSet<string>();

  foreach(var item in arr)
    if (!hs.Add(item)) {
      // User used "item" at least twice
      break; 
    }

1 Comment

btw; you can simplify to just if(!hs.Add(item)) { /* fail */ } - this avoids doing a separate Contains/Add test per item.
1

You can try using LINQ, something like this:

var query = arr.GroupBy(x=>x)
              .Where(g=>g.Count()>1)
              .ToList();

Comments

1

You can try :

  HashSet<String> hash = new HashSet<string>();

  string input = "TEST";
  bool found = false;

  foreach(string item in arr)
  {
      if (item.Equals(input))
      {
          if (hash.Contains(item))
          {
              Console.WriteLine("Already Taken");
          }
          else
          {
              hash.Add(item);
          }
          found = true;
          break;
      }
   }

  if (!found)
  {
      Console.WriteLine("Invalid Input");
  }

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.