C# LINQ Background Topics
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Exercise
Congratulations! You have made it through all the background material. You now know enough to not only use LINQ, but to even reimplement some elements of it yourself! Doesn't that sound exciting?
Let's try it out!
LINQ Select() method
One of the more commonly used methods in LINQ is the Select()
method. Select()
is an extension method to the IEnumerable<T>
interface. It is analogous to the map()
method found in many other programming languages.
Select()
takes each element, one-at-a-time, from a source IEnumerable<T>
sequence, applies a delegate function to the elements, and then returns an IEnumerable<U>
result.
NOTE: The type inside the collection can change, hence the change from
IEnumerable<T>
toIEnumerable<U>
.
Implement a Transform() method
In order to avoid the complications of dealing with generics in this exercise, let's limit the extension method to only work with IEnumerable<int>
. Here is what you need to do:
- Implement an extension to
IEnumerable<int>
calledTransform()
- The
Transform()
method should accept, as a parameter, a delegate that takes anint
input and returns anint
output - The
Transform()
method should be a generator that iterates through the inputIEnumerable<int>
, applies the delegate to each value, andyield return
s the result - The
Transform()
should return anIEnumerable<int>
output
Here are some examples to help you out
Example delegate declaration
private delegate int FuncTwoInts(int one, int two);
Example extension method
namespace IntExtensions
{
public static class CoolExtensionsForInt
{
public static string Growl(this int num, char a, char b)
{
return $"{a}{new string(b, num)}";
}
}
}
Example generator
public IEnumerable<int> GetDoubles(int n)
{
for (int i = 0; i < n; i++)
{
yield return i * 2;
}
}