8000 New IndexBy operator · Issue #560 · morelinq/MoreLINQ · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
New IndexBy operator #560
Closed
Closed
@leandromoh

Description

@leandromoh

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 }

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0