1
List<string> SampleList = new List<string>();
string tmpStr = "MyStringValue";

From this example, how to check the value of the string variable tmpStr if it's already in SampleList?

1
  • But I voted up for both of you! Thanks! Commented Sep 12, 2013 at 2:41

2 Answers 2

3

You could use the List<T>.Contains Method

if (SampleList.Contains(tmpStr))
{
    //  list already contains this value
}
else
{
    // the list does not already contain this value
}

If your objective is to prevent your list from containing duplicate elements at all times then you might consider using the HashSet<T> Class which does not allow for duplicate values.

Sign up to request clarification or add additional context in comments.

8 Comments

Oh ".Contains" is the key then. Thank you. I'm, totally new to List object.
Can you give me an example on how to use this HashSet<T> Class to my List?
@ChrisN.P. Here is a link to a comprehensive (much more so than I could be) beginners' tutorial: dotnetperls.com/hashset
Thanks. Let me check this then :)
Alright I decided to select your's for posting your solution first. ;)
|
3

Any particular reason for using List?

You can use a Set, Set<string> hs = new HashSet<string>(); and it will not allow duplicates.

Set<string> hs = new HashSet<string>();
hs.add("String1");
hs.add("String2");
hs.add("String3");

// Now if you try to add String1 again, it wont add, but return false.
hs.add("String1");

If you do not want duplicates for case insensitive elements use

HashSet<string> hs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

Hope that helps.

10 Comments

I used List to store all the items from the database.
Can I apply this approach to a List?
@ChrisN.P. With approach do you mean by not allowing duplicates?
Yes the one that you posted.
Set will be useful if you do not want duplicates. HashMap will be useful if you need to associate key-value pairs, for example, say String, and the occurrence of the String in the database. So it all depends on your use.
|

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.