1

Here is the original code I wrote (for test purpose):

        List<A037Line> a037Lines = new List<A037Line>();

        foreach (var textFile in propassBatchFolder.TextFiles)
        {
            foreach (var a037Line in textFile.A037Lines)
            {
                if (a037Line.NISS == "80061031738")
                {
                    a037Lines.Add(a037Line);
                }
            }
        }

Resharper suggests the following LINQ code instead:

        List<A037Line> a037Lines = (from textFile in propassBatchFolder.TextFiles
            from a037Line in textFile.A037Lines
            where a037Line.NISS == "80061031738"
            select a037Line).ToList();

As I'm a beginner in LINQ, what is the "dotted" version of this LINQ expression?

eg:

propassBatchFolder.TextFiles.Where(…).Select()….ToList()

Many thanks in advance :-)

Liam
  • 27,717
  • 28
  • 128
  • 190
lorcan
  • 359
  • 1
  • 3
  • 4
  • [convert LINQ expression into Lambda](http://stackoverflow.com/questions/1524813/convert-this-linq-expression-into-lambda) – huMpty duMpty Mar 30 '16 at 14:26
  • `from` is the collection, `where` goes in `.Where(x => x.whatever.is.in.the.where)` and `select` goes in `.Select(x => x.whatever.you.select)`. Try it. –  Mar 30 '16 at 14:26
  • I'm 95% sure resharper gives you the option of converting from query syntax to method syntax – Jonesopolis Mar 30 '16 at 14:30

2 Answers2

2

It is easier to convert nested loops to queries if you start from the inside.

Convert the inner loop first:

foreach (var textFile in propassBatchFolder.TextFiles) {
    a037Lines.AddRange(
        textFile.A037Lines.Where(a037Line => a037Line.NISS == "80061031738")
    );
}

Now you can convert the outer loop with an application of SelectMany:

var res = propassBatchFolder
    .TextFiles
    .SelectMany(textFile => textFile.A037Lines.Where(a037Line => a037Line.NISS == "80061031738"))
    .ToList();

Finally, you can reduce nesting by moving out the Where from inside SelectMany:

var res = propassBatchFolder
    .TextFiles
    .SelectMany(textFile => textFile.A037Lines)
    .Where(a037Line => a037Line.NISS == "80061031738")
    .ToList();

The end result would be the same, but the final version is more readable.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

I'm not 100% sure that it's the exact syntactical equivalent, but it's semantically the same:

List<A037Line> a037Lines = 
    propassBatchFolder.TextFiles.
        SelectMany(textFile => textFile.A037Lines).
        Where(a037Line => a037Line.NISS == "80061031738").
        ToList();
René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • 1
    According to [my translator](http://lq2m.azurewebsites.net/) the per-spec translation has some extra code to keep `textFile` in scope, but you're right, it's totally unnecessary. – Rawling Mar 30 '16 at 14:54