Skip to content

Instantly share code, notes, and snippets.

@LGM-AdrianHum
Last active November 4, 2015 03:27
Show Gist options
  • Save LGM-AdrianHum/3ed353036d21e5495e52 to your computer and use it in GitHub Desktop.
Save LGM-AdrianHum/3ed353036d21e5495e52 to your computer and use it in GitHub Desktop.
A LINQ/Tuple<> solution to FizzBuzz
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());
}
}
@LGM-AdrianHum
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment