Wednesday, February 27, 2019

Debugging Lambda / LINQ

Have you ever had a LINQ query or lambda expression and you couldn't for the life of you figure out why it wasn't working? To make debugging easier, you can actually set breakpoints on individual parts of the lambda expression. The query below is an example. Say that you're getting the error: System.FormatException: "Input string was not in a correct format."  Judging from that, you think it is probably the int.Parse that is causing the problem, but what is the value of the row that's having an issue? So, set a breakpoint on the .Parse (just select Parse and hit F9), and if you don't have a lot of rows you could easily find the row where the "amount" column contains a non-numeric value.

private void TestLambdaHowtoSetBreakpoint()
{
// Highlight one (or several) of the lambda parts of this LINQ query (such as the .Sum or the .Parse)
// and hit F9 to set breakpoints only on that part of the query! Awesome!
var sum = this.dtGlobal.AsEnumerable().Select(row => row)
.GroupBy(row => row.Field<string>("label"))
.ToDictionary(grp => grp.Key, intField => intField.Sum(row => int.Parse(row["amount"].ToString())));
}

Some people may be confused about the difference between lambda and LINQ. There is a good explanation in this StackOverflow thread (the second reply): https://stackoverflow.com/questions/34980144/difference-between-lambda-and-linq

I'll include some of that StackOveflow reply here:
----------------------------------------------------------------
This is LINQ:
var a = from b in someList
where b.Value == something
select b;

But it can be written with a lambda expression:
var a = someList.Where(b => b.Value == something);

The lambda part is b => b.Value == something.

Whereas:
mock.Setup(m => m.SomeOp()).Returns(new Thing()); 

uses a lambda expression (the m => m.SomeOp()), but has nothing to do with LINQ.

To make it easy, just remember that  => is the lambda operator.
----------------------------------------------------------------

That’s it! I hope you’ve learned something about debugging lambda expressions! Happy coding!  =0)

No comments:

Post a Comment