Wednesday, January 18, 2017

How to flatten a list of lists into a flat list in one line of code: SelectMany is your friend

Given that you have a list of lists, how do you flatten it?



how do you flatten it?


With the SelectMany LINQ method, it's easy peasy:

var listOfLists = new List<IEnumerable<int>>() { Enumerable.Range(1, 3), Enumerable.Range(20, 3) };
listOfLists.Dump("List of lists");
listOfLists.SelectMany(lol => lol).Dump("Flat list");

Download linqpad sample, here

Friday, January 13, 2017

Assigning lambda expression to a variable

In the spirit of writing terse code, I was pleasantly surprised that you can assign a lambda expression to a local variable. A quick sample:
void Main()
{
 Func<string, string> sayHello = ((input) => { return input + "!!"; });
 System.Diagnostics.Debug.WriteLine(sayHello("hello world"));
}

Results:
hello world!!

in Func<string, string>, the first string specifies the input parameter's data type, while the last string is for the return type. If you have more than one input parameter, you'd have multiple parameters specified like this <string, string, stringstring> and the last one is always for the return type of the function.

Wednesday, January 11, 2017

My FSharp patter matching code kata

Given a list of numbers, detect when the values 2,3,4 are present one after the other.

Thursday, January 05, 2017

Extension method to dump Highlighted search results in Linqpad

Here's an extension method which lets you output the found results as html.

For example, if you wanted to show the result of a search and replace, given:
 var text = "An apple a day keeps the doctor away\n you can say that any day of the year today or tomorrow.";
 var find = "day";
 var replace = "week";
 
 text.HighlightText(find).Dump("Original text");
 text.Replace(find, replace).HighlightText(replace).Dump("updated text");

The result would be:
Original text
An apple a 
day
 keeps the doctor away
 you can say that any 
day
 of the year.
updated text
An apple a 
week
 keeps the doctor away
 you can say that any 
week
 of the year.

See extension method below: