s-s
s-s

Reputation: 380

Add counter to Items In List by Key

I have object like this:

public class A
{
   public int KeyValue {get; set;}
   public int Counter {get; set;}
}

In the main program I have a list on A items for example:

List<A> list = new List<A> {new A{KeyValue  = 1},new A{KeyValue  = 2},new A{KeyValue  = 1},
new A{KeyValue  = 2},new A{KeyValue  = 1},new A{KeyValue  = 3}}

I want to add a counter for every item in the list, but for every key I need its own counter.

In the example above it will be: {1,1},{2,1},{1,2},{2,2}{1,3}{3,1}

I did this code, it works, by I wonder if there is a "nicer" one.

var grouped = list.GroupBy(a=>a.KeyValue);
foreach (var group in grouped)
{
   int counter = 1;
   foreach (var item in group)
   {
      item.Counter = counter++;
   }
}

Upvotes: 0

Views: 416

Answers (1)

Guru Stron
Guru Stron

Reputation: 142783

If order is not important and this code is not in performance critical part of application you can do some LINQ magic:

List<A> list = new[] { 1, 2, 1, 2, 1, 3 }
    .GroupBy(i => i)
    .SelectMany(g => g.Select((i, index) => new A
    {
        KeyValue = i,
        Counter = index + 1
    }))
    .ToList();

Otherwise with latest language version you can clean up code a little bit with target typed new expressions:

List<A> list = new()
{
    new() { KeyValue = 1 }, new() { KeyValue = 2 }, new() { KeyValue = 1 },
    new() { KeyValue = 2 }, new() { KeyValue = 1 }, new() { KeyValue = 3 }
};

Upvotes: 1

Related Questions