Tomas
Tomas

Reputation: 18127

Index duplicates from the list using Linq

Suppose I have a list of strings

var data = new List<string>{"fname", "phone",  "lname", "home", "home", "company", "phone", "phone"};

I would like to list all values and add index to duplicates like this

fname,
phone,
lname,
home,
home[1],
company,
phone[1],
phone[2]

or like this

fname,
phone[0],
lname,
home[0],
home[1],
company,
phone[1],
phone[2]

The both solutions would work for me.

Is that possible with Linq?

Upvotes: 0

Views: 33

Answers (1)

NetMage
NetMage

Reputation: 26926

You can use LINQ GroupBy to gather the matches, and then the counting version of Select to append the indexes.

var ans = data.GroupBy(d => d).SelectMany(dg => dg.Select((d, n) => n == 0 ? d : $"{d}[{n}]"));

Upvotes: 1

Related Questions