Closed
Description
Allow us to know the index of the elements inside their groups created by a keySelecton
function.
Prototype
static IEnumerable<TResult> IndexBy<T, TKey, TResult>(this
IEnumerable<T> source,
Func<T, TKey> keySelector,
Func<T, TKey, int, TResult> resultSelector)
{
return source
.Select((element, index) => new { element, index })
.GroupBy(pair => keySelector(pair.element))
.SelectMany(grup => grup.Select((pair, innerIndex) => new { pair, grup.Key, innerIndex }))
.OrderBy(x => x.pair.index)
.Select(x => resultSelector(x.pair.element, x.Key, x.innerIndex));
}
Example
var nomes = new[] { "ana", "beatriz", "carla", "bob", "davi", "adriano", "angelo", "carla", };
var resultado = nomes.IndexBy(x => x.First(), (nome, key, index) => new { nome, key, index });
outputs
{ nome = ana, key = a, index = 0 }
{ nome = beatriz, key = b, index = 0 }
{ nome = carla, key = c, index = 0 }
{ nome = bob, key = b, index = 1 }
{ nome = davi, key = d, index = 0 }
{ nome = adriano, key = a, index = 1 }
{ nome = angelo, key = a, index = 2 }
{ nome = carla, key = c, index = 1 }