简体   繁体   中英

How to check whether a list<string> is containing any string value or not

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.

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.

ie 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, ie

var uniqueList = someSourse.Distinct().ToList();

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?

List <string> lsLinks = new List<string>();
bool contains = lsLinks.Any(s => s.Equals("myString");

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.

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.

我不确定我是否了解您的需求,但是请尝试以下操作:

if(!lsLinks.Contains(NewString)) lsLinks.Add(NewString)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM