搜索列表对象
问题描述:
我有一个列表:搜索列表对象
Dim list As New List(Of String)
下列物品:
290-7-11
1255年7月12日
222- 7-11
290-7-13
什么是简单快捷的方式来搜索“第一个块”加上“ - ”加上“第二个块”的重复是否已经在列表中。示例项目290-7出现两次,290-7-11和290-7-13。
我正在使用.net 2.0
答
如果你只是想知道是否有重复,但不在乎它们是什么...
最简单的方法(假设正好有两个破折号)。
Boolean hasDuplicatePrefixes = list
.GroupBy(i => i.Substring(0, i.LastIndexOf('-')))
.Any(g => g.Count() > 1)
最快的方法(至少对于大型字符串集合)。
HashSet<String> hashSet = new HashSet<String>();
Boolean hasDuplicatePrefixes = false;
foreach (String item in list)
{
String prefix = item.Substring(0, item.LastIndexOf('-'));
if (hashSet.Contains(prefix))
{
hasDuplicatePrefixes = true;
break;
}
else
{
hashSet.Add(prefix);
}
}
如果有两个以上破折号的情况,请使用以下内容。这仍然会失败,只有一个破折号。
String prefix = item.Substring(0, item.IndexOf('-', item.IndexOf('-') + 1));
在.NET 2.0使用Dictionary<TKey, TValue>
代替HashSet<T>
。
Dictionary<String, Boolean> dictionary= new Dictionary<String, Boolean>();
Boolean hasDuplicatePrefixes = false;
foreach (String item in list)
{
String prefix = item.Substring(0, item.LastIndexOf('-'));
if (dictionary.ContainsKey(prefix))
{
hasDuplicatePrefixes = true;
break;
}
else
{
dictionary.Add(prefix, true);
}
}
如果你不关心的可读性和速度,使用数组而不是列表,你是正则表达式的一个真正的球迷,你可以做到以下几点,太。
Boolean hasDuplicatePrefixes = Regex.IsMatch(
String.Join("#", list), @".*(?:^|#)([0-9]+-[0-9]+-).*#\1");
答
是否要停止添加用户?
如果是这样,一个HashTable的关键字作为第一个块 - 第二块可能是有用的。
如果不是,LINQ是要走的路。
但是,它将不得不遍历列表来检查。
此列表有多大?
编辑:我不知道如果HashTable具有通用版本。
您也可以使用可以采用泛型参数的SortedDictionary。
答
如果你列表只包含字符串,那么你可以简单地做,把你想用列表来查找沿字符串的方法:
Boolean isStringDuplicated(String find, List<String> list)
{
if (list == null)
throw new System.ArgumentNullException("Given list is null.");
int count = 0;
foreach (String s in list)
{
if (s.Contains(find))
count += 1;
if (count == 2)
return true;
}
return false;
}
如果你的数字有在你的程序中有特别的意义,不要害怕用班级来代表他们,而不是坚持使用字符串。然后,您将有一个地方为所述数字编写所需的所有自定义功能。
这个清单不是那么大,最多100件。我正在使用.net 2.0 – 2009-07-23 19:38:28
是的。我想阻止用户添加它。 – 2009-07-23 19:39:53