mark.a
mark.a

Reputation: 15

Add an index to duplicate elements of a string list in C#

I need help with an algorithm that will add an index to the duplicate elements in a string list in C#.

i.e.

A, B, C, D, A, B, E, F, A

will become

A, B, C, D, A (1), B (1), E, F, A (2)

Upvotes: 0

Views: 330

Answers (3)

codingbiz
codingbiz

Reputation: 26386

Using Lamba/LINQ

  string x = "A, B, C, D, A, B, E, F, A";
  x = x.Replace(" ", "").Replace(",", ""); //Remove the spaces and commas
  var l = x.Select((v, i) => String.Format("{0}({1})", v, x.Substring(0, i).Count(c => c.Equals(v))));

  var s = l.Select(c=>c.Replace("(0)","")).ToArray();
  string result = String.Join(", ", s);

Upvotes: 1

Cole Cameron
Cole Cameron

Reputation: 2233

var strings = new string[] { "A", "B", "C", "D", "A", "B", "E", "F", "A" };

Dictionary<string, int> counts = new Dictionary<string, int>();
for (int i = 0; i < strings.Length; ++i)
{
    if (counts.ContainsKey(strings[i]))
        strings[i] = string.Format("{0} ({1})", strings[i], counts[strings[i]]++);
    else
        counts.Add(strings[i], 1);
}

Upvotes: 0

Haedrian
Haedrian

Reputation: 4328

Dictionary<char,int> counts = new Dictionary<char,int>();

foreach (char c in myCharArray)
{
if (counts.Keys.Contains(c))
{
counts[c]++;
myOutputList.Add(c + "(" + counts[c] + ")");
}
else 
{
counts.Add(c,0);
}

}

Added:

What I'm basically doing is going through the array one character at a time. I'm keeping a count of 'times I've seen each character' in the dictionary - which I increment every time I see a new one.

When I see one which I've seen already - I add the number in brackets as requested.

Upvotes: 2

Related Questions