patterncsharpMinor
Beginner's LINQ exercise to print the odd numbers in descending order
Viewed 0 times
linqtheorderdescendingnumbersexercisebeginnerprintodd
Problem
I'm going through C# Operators which led me to more specifically Lambda Expressions (C# Programming Guide). I've modified one of the examples from just getting the
.Count to printing out the odd numbers. Is there anything I can do to simplify my code? Should I "method chain" oddNumbers and oddDescending together? I've left them apart since I'm just learning and seeing them separate is easier for me to understand right now.class Program
{
public static void Main(string[] args)
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var oddNumbers = numbers.Where(x => x % 2 == 1);
var oddDescending = oddNumbers.OrderByDescending(x => x);
foreach (int odd in oddDescending)
{
Console.WriteLine(odd);
}
}
}Solution
People will commonly create an Extension method for
With this in hand, you can go all out on your filter & map.
Note that I did extract a method so we could name the filter. It makes it a bit more readable (and as an added bonus, reusable).
You may be asking yourself why naming the predicate is better than using a variable. Other than reuse, the benefit is that there's no need to store any state. At its heart, Linq is a functional way to program, so it's good to embrace it.
IEnumerable to add a map method that behaves much like the IList.ForEach method. public static class IEnumerableExtensions {
public static void ForEach(this IEnumerable source, Action action) {
foreach(item in source) action(item);
}
}With this in hand, you can go all out on your filter & map.
class Program
{
public static void Main(string[] args)
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
numbers.Where(IsOdd)
.OrderByDescending(x => x)
.ForEach(Console.WriteLine);
}
private static bool IsOdd(int x) => x % 2 == 1;
}Note that I did extract a method so we could name the filter. It makes it a bit more readable (and as an added bonus, reusable).
You may be asking yourself why naming the predicate is better than using a variable. Other than reuse, the benefit is that there's no need to store any state. At its heart, Linq is a functional way to program, so it's good to embrace it.
Code Snippets
public static class IEnumerableExtensions {
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
foreach(item in source) action(item);
}
}class Program
{
public static void Main(string[] args)
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
numbers.Where(IsOdd)
.OrderByDescending(x => x)
.ForEach(Console.WriteLine);
}
private static bool IsOdd(int x) => x % 2 == 1;
}Context
StackExchange Code Review Q#162078, answer score: 6
Revisions (0)
No revisions yet.