我知道stackoverflow上有大量关于这个主题的类似问题,但我却没有找到我想要的答案。这是我的需求。
我有一个长列表的字符串(很容易超过50,000甚至100,000项),我需要在其中找到重复的项目。但仅仅找到重复的项目不够;我真正想做的是遍历列表并在每个项目的末尾添加一个递增的索引,以指示该项目重复的次数。为了更好地说明这一点,让我举个例子。实际上,我的列表包含路径,所以这个例子大致类似于这种情况。
我原来的列表:
AAA\BBB
AAA\CCC
AAA\CCC
BBB\XXX
BBB
BBB\XXX
BBB\XXX
我添加了索引的调整列表:
AAA\BBB[1]
AAA\CCC[1]
AAA\CCC[2]
BBB\XXX[1]
BBB[1]
BBB\XXX[2]
BBB\XXX[3]
首先我尝试使用Linq方法:
List<string> originalList = new List<string>();
List<string> duplicateItems = new List<string>();
// pathList is a simple List<string> that contains my paths.
foreach (string item in pathList)
{
// Do some stuff here and pick 'item' only if it fits some criteria.
if (IsValid(item))
{
originalList.Add(item);
int occurences = originalList.Where(x => x.Equals(item)).Count();
duplicateItems.Add(item + "[" + occurences + "]");
}
}
这段代码能够有效地给出所需的结果,但是如果我的列表包含了10万个元素,它会变得相当缓慢。因此,我查找了相关资料并了解到HashSet可能是一个更高效的替代方案。但是我不知道如何使用HashSet来得到我需要的确切结果。
我想我可以尝试像这样做:
HashSet<string> originalList = new HashSet<string>();
List<string> duplicateItems = new List<string>();
foreach (string item in pathList)
{
// Do some stuff here and pick 'item' only if it fits some criteria.
if (IsValid(item))
{
if (!originalList.Add(item))
{
duplicateItems.Add(item + "[" + ??? + "]");
}
}
}
稍后我可以向HashSet中的所有项目添加“[1]”,但是当将项目添加到我的重复列表中时,如何使索引正确(如上面的普遍困惑标志“?”所示)?由于在我的示例中可能会有数百个不同的重复项,每个重复项重复的次数都不同,因此我无法保留可以传递给方法的引用int。
我是否仍然可以使用HashSet,或者有更好的方法来完成我的目标?即使是指向正确方向的轻微提示也将是一大帮助。
HashSet<string>
来存储原始列表,因为HashSet<T>
不会存储重复项。 - itsme86