Last active
November 4, 2015 03:27
-
-
Save LGM-AdrianHum/3ed353036d21e5495e52 to your computer and use it in GitHub Desktop.
A LINQ/Tuple<> solution to FizzBuzz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void DoFizzBuzz() | |
{ | |
var combinations = new List<Tuple<int, string>> | |
{ | |
new Tuple<int, string> (3, "Fizz"), | |
new Tuple<int, string> (5, "Buzz"), | |
}; | |
Func<int, int, bool> isMatch = (i, comb) => i % comb == 0; | |
for (int i = 1; i <= 100; i++) | |
{ | |
var matchingCombs = combinations.Where(c => isMatch(i, c.Item1)).ToList(); | |
Console.WriteLine(matchingCombs.Any() ? string.Join("", matchingCombs.Select(c => c.Item2)) : i.ToString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I looked at writing the following code with the KeyValuePair; however when I bench marked the performance of the KVP against the Tuple. The comparison is relevant only in cases where a Tuple of two items is used. Tuples passed as part of functions (especially Linq/Lambda functions) perform better than KeyValuePairs.
The main advantage that I need to point out is that A tuple can return multiple values (with less code than a class would require). But using the c.Item1, c.Item2, c.Item3 syntax may seem a little funky.