Skip to content

Default elements from a secondary source #997

Description

@atifaziz

I'd like to propose an operator called Default that defaults an element from a secondary sequence when an element from the source sequence is deemed missing or faulty. A function is used to determine if an element of the source sequence is deemed missing or faulty and another function projects a result given the missing/faulty element and a default from secondary sequence for substitution/replacement.

A prototype would be as follows:

public static IEnumerable<TResult>
    Default<TSource, TDefault, TResult>(this IEnumerable<TSource> source,
                                        IEnumerable<TDefault> defaults,
                                        Func<TSource, (bool, TResult)> chooser,
                                        Func<TSource, TDefault, TResult> defaultor)
{
    using var @default = defaults.GetEnumerator();
    foreach (var item in source)
    {
        if (chooser(item) is (true, var v))
        {
            yield return v;
        }
        else
        {
            if (!@default.MoveNext())
                break;
            yield return defaultor(item, @default.Current);
        }
    }
}

The following code demonstrates the operator in action:

var source = new string?[] { "foo", null, "bar", "baz", null };
var nums = Enumerable.Range(1, int.MaxValue);

foreach (var e in source.Default(nums, s => (s is not null, s), (_, r) => $"unnamed{r}"))
    Console.WriteLine(e);

Outputs:

foo
unnamed1
bar
baz
unnamed2

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions