Functional Linq tips for senior C# developers
Here are some basic tips for senior developers, who want to understand, and potentially use Linq native query syntax in their code, beyond the standard IEnumerable implementation.
1. Linq support for select
Did you know that if you implement Select method in any type you can use the from …in …select Linq syntax ???
I will take a random data straucture like this Func<List<int>> and add linq query support. First of all i can make it into a functor and use Linq’s select by adding this extension method :
public static Func<List<T1>> Select<T,T1>
(this Func<List<T>> x, Func<T,T1> func)
{
return ()=>(x()).Select(i=>func(i)).ToList(); }
and then its perfectly valid to write this :
Func<List<int>> f1 = ()=>new List<int>{7,8,9,2}; var r = from c in f1 select c;
As a summary if i get a data structure and add a Mapping method then this is a functor
Data Structure + Select (aka Map) Method = A Functor
You can see more here about functor in c# functional programming.
2. Linq support for Filtering
In C# if you implement a Method
public Functor<T> Where(Func<T, bool> predicate)
you can use the from …in …where …select Linq syntax . If we continue extending our previous example, by adding this :
public static Func<List<T>> Where<T>
(this Func<List<T>> x,
Func<T, bool> predicate)
{
return () => x().Where(predicate).ToList();
}
we can write now
var filterResult = from c in f1 where c ==2 select c ;
3. Linq Support For Monads
Now in order to write something like this
Func<List<T>> monadincResult =
from x in f1
from y in f2
where x ==2
select x+ y;
which means we combine two of our functors into a single one, we must provide a “simple” method that will do this mixing. In Linq this is called SelectMany. By providing a SelectMany the functor now has been upgraded practically to a Monad, as far as we are concerned.
Data Structure + Select (aka Map) +SelectMany (aka Bind) = Monad
i did this it for this random Func<List<int>> functor that now became this “lazy list monad” for lack of better wording. It looks like that :
you can try it, or play around, in this .net fiddle .
Conclusion :
I am not saying that you have to, or even need to use Linq syntax in your project data structures. But as a senior c# developer, one must be familiar with this concept and have an advanced understanding on how Linq works, also it offers a fundamental understanding of Functors and Monads .
Its very useful to know that you can make up a monad by just Implementing the SelectMany method, which is not always easy.
you can learn more about Functors and monads here :
feel free to connect with me in LinkedIn