I have the following array:
Driver[] predictions = new Driver[6];
predictions[0] = new Driver(10, "Michael Schumacher");
predictions[1] = new Driver(10, "Michael Schumacher");
predictions[2] = new Driver(9, "Fernando Alonso");
predictions[3] = new Driver(8, "Jensen Button");
predictions[4] = new Driver(7, "Felipe Massa");
predictions[5] = new Driver(6, "Giancarlo Fisichella");
I want to get all the duplicates – The name once, and then the positions (index) where the duplicates are. So, in this case I want to get “Michael Schumacher” and the positions 1 and 2 (index 0 and 1).
Can this be done in one go, or do I need to consider other options? I just read on DotNetPearls that IndexOf is pretty slow compared to having your own logic.
var driversSelectedMoreThanOnceAndTheirPositions = predictions.Select((driver, index) => new { driver, index })
.GroupBy(item => item.driver.Name)
.Where(grp => grp.Count() > 1)
.ToDictionary(g => g.Key, g => g.Select(a => (a.index + 1)).ToList());
To utilize linq for this, you could write something like the following, which uses an overload of
Selectthat allows you to get the element index and then performs aGroupByoperation.This will result in a sequence of anonymous-typed objects with the properties
Which you could use as in
You can, of course, change the way you group to get the entire driver object.