Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New IndexBy operator #560

Closed
leandromoh opened this issue Feb 18, 2019 · 1 comment
Closed

New IndexBy operator #560

leandromoh opened this issue Feb 18, 2019 · 1 comment
Assignees
Milestone

Comments

@leandromoh
Copy link
Collaborator

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 }
@atifaziz
Copy link
Member

atifaziz commented Feb 20, 2019

This is interesting and I would welcome a PR!

This was referenced Mar 13, 2019
@atifaziz atifaziz added this to the vNext milestone May 21, 2019
@atifaziz atifaziz modified the milestones: vNext, 3.2.0 Jul 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants