0

Is it possible to write this lambda in a more generic way? It works fine, but seems too specifically typed; the content of the IEnumerables are not touched, but should be preserved in the return type.

static readonly Func<
    (IEnumerable<string>, IEnumerable<string>),
    (IEnumerable<string>, IEnumerable<string>),
    (IEnumerable<string>, IEnumerable<string>)
> JoinListTuples = (a, b) =>
    (a.Item1.Concat(b.Item1),
        b.Item2.Concat(b.Item2));

I was thinking of something like this, but it doesn't compile:

static readonly Func<
    (IEnumerable<T>, IEnumerable<U>),
    (IEnumerable<T>, IEnumerable<U>),
    (IEnumerable<T>, IEnumerable<U>)
> JoinListTuples = (a, b) =>
    (a.Item1.Concat(b.Item1),
        b.Item2.Concat(b.Item2));
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Robert K. Bell
  • 9,350
  • 2
  • 35
  • 50

2 Answers2

4

Types can be generic, methods can be generic, but fields cannot be generic.

A workaround when you really need to have this generically as a delegate type is to make it a field of a generic class:

public static class HelperClass<T, U> {
    public static readonly Func<
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>)
    > JoinListTuples = (a, b) =>
        (a.Item1.Concat(b.Item1),
            b.Item2.Concat(b.Item2));
}

But for most purposes, it would suffice to just turn it into a method instead. Perhaps something like this:

static (IEnumerable<T>, IEnumerable<U>) JoinListTuples<T, U>(
    (IEnumerable<T>, IEnumerable<U>) a,
    (IEnumerable<T>, IEnumerable<U>) b)
{
    return (a.Item1.Concat(b.Item1),
        b.Item2.Concat(b.Item2));
}
Robert K. Bell
  • 9,350
  • 2
  • 35
  • 50
2

I'm not sure if this will help you

However, something like this maybe

public class SomeHelper<T,U>
{

    public static readonly Func<
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>),
        (IEnumerable<T>, IEnumerable<U>)> 
            JoinListTuples = (a, b) => 
               (a.Item1.Concat(b.Item1),b.Item2.Concat(b.Item2));

}

Note, untested and not in front of VS

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 1
    Heh, you beat me to it. Yes, that compiles exactly the way you have it now. –  May 31 '18 at 23:44