如何检查列表<string>是否包含任何字符串值

Mon*_*RPG 1 c# string contains list .net-4.0

下面的代码是list元素.

List <string> lsLinks = new List<string>();
Run Code Online (Sandbox Code Playgroud)

在添加新字符串之前,我想检查列表是否包含我要添加的字符串.我怎样才能以最有效的方式做到这一点.

我可以遍历整个列表并检查,但我认为这不会是性能明智的.

Mar*_*ell 11

最有效的方法是简单地使用HashSet<T>两种,而不是列表(如果顺序并不重要),或在除到列表中,如果它.

HashSet<string> lsLinks = new HashSet<string>();
// now just Add() all you like; only ever one of each, but order is not defined
Run Code Online (Sandbox Code Playgroud)

要么

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);
Run Code Online (Sandbox Code Playgroud)

您也可以.Distinct()在LINQ中找到用途,即

var uniqueList = someSourse.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 6

如果你到有List<string>,你不能先进行排序,然后还有什么可以做,这将是比简单更快速Contains其将向整个列表.如果列表已排序,则可以执行二进制搜索.

如果你可以使用a HashSet<string>,那么随着集合变大,这显然会更快.(对于小集,性能差异可能无关紧要.)

请注意,HashSet<T>没有保留元素的顺序,但-所以,如果这对你很重要,你可能希望保持一个HashSet<string> 一个List<string>.然后你可以这样做:

if (stringSet.Add(newValue))
{
    stringList.Add(newValue);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果您目前只关注摘要中的性能,则应设置适当的目标以确定足够快的速度,并根据这些目标进行衡量 - 同时编写最简单的代码.您知道该列表实际上会在您的实际应用程序中变大吗?