0

I got a List<string> named Test:

List<string> Test = new List<string>();

I want to add a string to it using Test.Add();, but first I want to check if it already exists in the list.

I thought of something like this:

if (Test.Find("Teststring") != true)
{
   Test.Add("Teststring");
}

However, this returns an error.

jacobz
  • 3,191
  • 12
  • 37
  • 61

5 Answers5

3

I assume that you if you don't want to add the item if it is already added

Try This:

if (!Test.Contains("Teststring"))
{
   Test.Add("Teststring");
}
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
2

Any receives a Predicate. It determines if any element in a collection matches a certain condition. You could do this imperatively, using a loop construct. But the Any extension method provides another way. See this:

bool b1 = Test.Any(item => item == "Teststring");

Also you can use :

if (!Test.Contains("Teststring"))
{
...
    }
2

If you don't want to add an item twice it is a good indicator that you might use a HashSet<T> instead which is more efficient but doesn't allow duplicates(like a Dictionary with only keys).

HashSet<string> Test = new HashSet<string>();
bool newString = Test.Add("Teststring");

If you need to use the list use List.Contains to check if the string is already in the list.

What is the difference between HashSet and List in C#?

But your code suggests that you only want to add duplicates. I assume that this is not intended.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

In my opinion you are using the wrong datastructure here. You should use Hashset to avoid duplicates.

The lookup time for Hashset is O(1) whereas for list it is O(n)

The HashSet class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

This is how your code should look like.

HashSet<string> Test = new HashSet<string>();
Test.Add("Teststring");
Ehsan
  • 31,833
  • 6
  • 56
  • 65
0

Use Test.Contains("TestString");

sh_kamalh
  • 3,853
  • 4
  • 38
  • 50