方法查找/消除重复字符串

本文关键字:字符串 查找 方法 | 更新日期: 2023-09-27 18:05:40

我试图找到一个解决方案,在消除重复的字符串名称,说,例如,在文字字段中,我填充了特定文章历史版本贡献者的名字,因此,如果"ron"为文章的版本控制贡献了3次,则将名称"ron"添加到该文字控件中,并输出"ron"3次。

我试图找到,如果一个名字是重复两次,我应该能够填充它只有一次。

方法查找/消除重复字符串

我建议您使用字典,其键将是作者名称(或您不想重复的字段),值将是贡献者列表。例如,

Dictionary<string, List<Contributor>> contributors 
           = new Dictionary<string, List<Contributor>>();

Contributor contributor = new Contributor("ron", /*other values*/);
if ( !contributors.ContainsKey(contributor.Name) )
     contributors.Add(contributor.Name,new List<Contributor>());
contributors[contributor.Name].Add(contributor);

根据您的设置,我要么使用StringCollection,只是检查名称是否存在之前插入或只是将所有名称添加到列表并调用Distinct()(扩展方法在System.Linq)。所以:

StringCollection Names=new StringCollection();
if(!Names.Contains(Name))
   Names.Add(Name);

正如CharithJ所建议的,或者:

List<string> Names=new List<string>();
Names.Add(Name);
...
foreach(string Name in Names.Distinct())
{
...
}

都可以。

使用c# .Contains()函数检查名称是否已经添加到字符串

创建您想要实现的模型(它就像一个视图模型),它驱动您的"报告"的呈现。然后,模型可以控制"每个名字只输出一次"的需求。伪代码:

var ron = new Author("ron");
var ronnie = new Author("ronnie");
var report = new HistoryReport();
report.AddVersion(1, ron);
report.AddVersion(2, ron);
report.AddVersion(3, ronnie);
string renderedReport = report.Render();
// output e.g.: 
//   Versions 1 and 2 by ron; Version 3 by ronnie

然后使用该输出填充文字控件。

如果您使用简单的字符串替换,您将混淆ronronnie

StringCollection authors= new StringCollection();
if (!authors.Contains("Ron"))
{
    authors.Add("Ron");
}