Reputation: 1931
I am trying to find a solution, in eliminating repetitive string names, say for ex., in a literal field, i am populating names of the contributor of certain article's history version, and so, if "ron" has contributed to the versioning of an article 3 times, the name "ron" gets added to this literal control, and outputs "ron" 3 times.
I am trying to find, if a name is repeating twice, i should be able to populate it only one time. How can i achieve this ?
Upvotes: 2
Views: 252
Reputation: 1078
Depending on your setup, I'd either use a StringCollection and just check if the name exists prior to insertion or just add all the names to a List and call Distinct() (extension method in System.Linq). So either:
StringCollection Names=new StringCollection();
if(!Names.Contains(Name))
Names.Add(Name);
As CharithJ suggests, or:
List<string> Names=new List<string>();
Names.Add(Name);
...
foreach(string Name in Names.Distinct())
{
...
}
Either would work well enough.
Upvotes: 1
Reputation: 361382
I would suggest you to use dictionary whose keys will be the author name (or the field which you don't want to be repetitive) and values will be the lists of contributors. For example,
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);
Upvotes: 2
Reputation: 47520
StringCollection authors= new StringCollection();
if (!authors.Contains("Ron"))
{
authors.Add("Ron");
}
Upvotes: 0
Reputation: 56467
Create a model of what you want to achieve (it's like a view model) that drives the rendering of your "report". Then, the model can control this requirement of "only output each name once". Pseudo-code follows:
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
Then you use that ouput to populate your literal control.
If you use simple string substitution, you'll mix up ron
with ronnie
.
Upvotes: 0
Reputation: 28635
Use C#s .Contains() function to check if the name has already been added to the string
Upvotes: 0