Home > Enterprise >  C# LINQ zip function equivalent in query expression
C# LINQ zip function equivalent in query expression

Time:09-17

I can join elements of two lists with the Zip function; line1 from file1 with line1 with file2, etc.

var res = lines1.Zip(lines2, (x, y) => $"{x} {y}");

Is there a way to do in a query expression?

var res = from e1 in lines1
          where !string.IsNullOrWhiteSpace(e1)
          from e2 in lines2
          where !string.IsNullOrWhiteSpace(e2)
          select $"{e1} {e2}";

This joins each line from list1 with each line from list2, which is not what I need.

CodePudding user response:

Unfortunately the query syntax doesn't support everything that is available through the method syntax (e.g. Zip() method, self-written extension methods or 3rd party libraries like MoreLinq).

Due to this limitation it is not possible to get this functionality into C# by the user. Instead Microsoft as owner of the language had to implement such an functionality like it is described here.

CodePudding user response:

If you squint pretty hard then this is close:

IEnumerable<string> filtered1 =
    from e1 in lines1
    where !string.IsNullOrWhiteSpace(e1)
    select e1;

IEnumerable<string> filtered2 =
    from e2 in lines2
    where !string.IsNullOrWhiteSpace(e2)
    select e2;

IEnumerable<string> res =
    from x in filtered1.Zip(filtered2, (e1, e2) => (e1, e2))
    select $"{x.e1} {x.e2}";
  • Related