Reputation: 23800
The below code is list element.
List <string> lsLinks = new List<string>();
Before adding new strings i want to check whether list is containing the string i am going to add or not. How can i do that with most efficient way.
I can iterate through whole list and check but i think that would not be performance wise.
Upvotes: 1
Views: 1565
Reputation: 379
You could use HashSet instead of List<> if you don't care order of items. That collection has especially designed for best speed in comparison operations as it uses hashes.
Upvotes: 2
Reputation: 32878
You can use the following:
lsLinks.Contains(myString);
or
lsLinks.Where(o=>o==myString);
But if your goal is to ensure unique strings, you can use a HashSet instead rather than a List, if the order of strings is unimportant.
Upvotes: 2
Reputation: 4523
I am not sure I understood what you wanted, but try this :
if(!lsLinks.Contains(NewString)) lsLinks.Add(NewString)
Upvotes: 1
Reputation: 4090
List <string> lsLinks = new List<string>();
bool contains = lsLinks.Any(s => s.Equals("myString");
Upvotes: 2
Reputation: 1499770
If you've got to have a List<string>
, and you can't sort it first, then there's nothing you can do that will be faster than a simple Contains
which walks the whole list. If the list is sorted, you could perform a binary search instead.
If you can use a HashSet<string>
instead, that will obviously be a lot quicker as the set gets larger. (For small sets the performance difference is likely to be irrelevant.)
Note that a HashSet<T>
does not preserve the order of the elements though - so if that's important to you, you may want to keep a HashSet<string>
and a List<string>
. Then you can do:
if (stringSet.Add(newValue))
{
stringList.Add(newValue);
}
Note that if you're currently just concerned about the performance in the abstract, you should set appropriate goals to determine what is fast enough, and measure against those goals - while writing the simplest possible code. Do you know that the list will actually become large in your real application?
Upvotes: 6
Reputation: 1062502
The most efficient way would be to simply use a HashSet<T>
, either instead of the list (if order doesn't matter), or in addition to the list, if it does.
i.e. either
HashSet<string> lsLinks = new HashSet<string>();
// now just Add() all you like; only ever one of each, but order is not defined
or
List<string> lsLinks = new List<string>();
HashSet<string> unique = new HashSet<string>();
// now, when needed, check if the item is new to "unique"
if(unique.Add(newValue)) lsLinks.Add(newValue);
You might also find a use for .Distinct()
in LINQ, i.e.
var uniqueList = someSourse.Distinct().ToList();
Upvotes: 11