Skip to content

Instantly share code, notes, and snippets.

@daniel-packard
Last active June 21, 2016 19:02
Show Gist options
  • Save daniel-packard/15e147f20483bfd126c86801e52b6aaa to your computer and use it in GitHub Desktop.
Save daniel-packard/15e147f20483bfd126c86801e52b6aaa to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace LambdaTest2
{
class Program
{
static void Main(string[] args)
{
var digits = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// we can now query this list with LINQ methods
// e.g. digits.Where(...)
// Where() is a templated LINQ method (templated on the type of data source you have)
// In this case, since we have a list of integers -- the argument to Where() must be
// a function that takes an int and returns a bool (or, a Func<int, bool>)
// That function is evaluated for each item in the list, items that return true are
// kept, items that return false are discarded.
// you can pass in a function that's defined elsewhere (as in IsEven(..) defined below
var evenDigits = digits.Where(IsEven);
evenDigits.ToList().ForEach((input) => Console.Write($" {input}"));
Console.WriteLine();
// OR you can define the function inline with a lambda
var evenDigitsLambda = digits.Where((input) => (input % 2) == 0);
evenDigitsLambda.ToList().ForEach((input) => Console.Write($" {input}"));
Console.WriteLine();
// the above two options are equivalent -- but the lambda is often preferred
// because it is more compact, and keeps the logic right where it's being used
// the function delegate would be more common if the same logic is reused in many places.
// You can also combine the two using good judgement, as in:
var evenDigitsGreaterThan3AndLessThan7 = digits.Where((input) => IsEven(input) && IsLessThanSeven(input) && IsGreaterThanThree(input));
evenDigitsGreaterThan3AndLessThan7.ToList().ForEach((input) => Console.Write($" {input}"));
Console.WriteLine();
Console.ReadKey();
// that gives you a TON of flexibility to define core reusable logic, and compose it in different ways
}
private static bool IsEven(int input)
{
return (input % 2) == 0;
}
private static bool IsGreaterThanThree(int input)
{
return input > 3;
}
private static bool IsLessThanSeven(int input)
{
return input < 7;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment