C# LINQ Background Topics

player_one
1,024 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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> to IEnumerable<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> called Transform()
  • The Transform() method should accept, as a parameter, a delegate that takes an int input and returns an int output
  • The Transform() method should be a generator that iterates through the input IEnumerable<int>, applies the delegate to each value, and yield returns the result
  • The Transform() should return an IEnumerable<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;
    }
}
Putting It Together Exercise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Collections.Generic;
namespace Background1
{
// Uncomment the TransformationFunction delegate declaration
//
// following the examples in the lessons, declare the type
// TransformationFunction as a delegate that takes a single
// int parameter and returns an int result.
// public ... TransformationFunction ...
// Write the extension method (and containing class) here,
// following the examples in the lessons. The method should
// be called Transform(), extend IEnumerable<int>, take an
// extra parameter of type TransformationFunction, and
// return an IEnumerable<int>.
// public ... class ...
// { }
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content