C# Lambda Expression One-Liners

LINQ is a very popular feature of C#. You can write complex code in a lesser line. In this post, I will show you some one-liner Lambda expression.

Write a factorial function using the lambda expression

Func<int, int> fact =  null;

fact = x => x ==  0  ?  1  : x *  fact(x -  1);

The function that prints the nth Fibonacci number

Func<int, int> Fib =  null;

Fib = (n) => n ==  0  || n ==  1  ?  1  :  Fib(n -  1) +  Fib(n -  2);

Function checks that number is odd or even

Func<int, bool> IsOdd =  null;

IsOdd = x => x %  2  !=  0;

Merge two arrays into a single array

          int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
          Func<int[], int, int[]> MultiplyEachArrayElement = null;
          MultiplyEachArrayElement = (n, i) => n.Select(x => x * i).ToArray();

          //Merge Two array into single array
          int[] arr2 = new int[] { 1, 2, 3, 4, 5, 6 };
          Func<int[], int[], int[]> Merge = null;
          Merge = (x, y) => x.Zip(y, (a, b) => a + b).ToArray();
   

Find the length of the given string

Func<string, int> Length =  null;

Length = str => str.Length;

Convert sentence into a word

Func<string, char[], string[]> Sentence =  null;

Sentence = (x, s) => x.Split(s);

Find Gcd of two given numbers

Func<int, int, int> Gcd =  null;

Gcd = (a, b) => b ==  0  ? a :  Gcd(b, a % b);

Find LCM of two given number

Func<int, int, int> LCM =  null;
LCM = (a, b) => (a * b) /  Gcd(a, b);

Function for downloading data from given URL

Func<string, string> Download =  null;

Download = (x) =>  new  WebClient().DownloadString(x);

Function for finding max of two number

Func<int, int, int> Max =  null;

Max = (x, y) => x > y ? x : y;

Function for finding max of three numbers

Func<int, int, int, int> MaxOfThree =  null;

MaxOfThree = (x, y, z) => x > y & y > z ? x : x < y && x > y ? y : z;

Console.WriteLine(MaxOfThree(1, 2, 038));

Function for summing array elements

Func<int[], int> Sum =  null;

Sum = (x) => x.Sum();

Power function

Func<int, int, int> Power =  null;

Power = (x, y) => y ==  0  ?  1  : x *  Power(x, y -  1);

Find the extension of the given filename

Func<string, string> FileExtension =  null;

FileExtension = (x) => x.Split('.')[1];

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru