Recent Changes - Search:

Oktatás

* Programozás 2
  + feladatsor
  + C feladatsor
  + Python feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

* levelezősök
  + Adator. prog.
  + feladatsor
  + quick link

teaching assets


Félévek

* 2024/25/1
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

20180412c

Select (in other languages: map)

using System.Linq;    // you need this for Select

csharp> new[] { 1, 2, 3 }.Select(x => x * x)
{ 1, 4, 9 }

csharp> new[] { 1, 2, 3 }.Select(x => x * x).GetType()
System.Linq.Enumerable+SelectArrayIterator`2[System.Int32,System.Int32]

csharp> new[] { 1, 2, 3 }.Select(x => x * x).ToList()
{ 1, 4, 9 }

Let's see this line:

csharp> new[] { 1, 2, 3 }.Select(x => x * x)
{ 1, 4, 9 }

x => x * x is a lambda, with input, arrow (=>), and output. That is, take every element of the array (x) and calculate its square (x * x). The result is an iterator that you can convert to a list if you want.

Another example:

csharp> new[] { 1, 2, 3 }.Select(n => n.ToString())
{ "1", "2", "3" }

In other languages it's usually known as "map" function (not to be confused with HashMap).


Let's implement this function without using LINQ. This is for educational purposes.

Here are some tests first:

[Fact]
public void Accumulate_squares()
{
    Assert.Equal(new[] { 1, 4, 9 }, new[] { 1, 2, 3 }.Accumulate(x => x * x));
}

[Fact]
public void Accumulate_upcases()
{
    Assert.Equal(new List<string> { "HELLO", "WORLD" }, new List<string> { "hello", "world" }.Accumulate(x => x.ToUpper()));
}

[Fact]
public void Accumulate_allows_different_return_type()
{
    Assert.Equal(new[] { "1", "2", "3" }, new[] { 1, 2, 3 }.Accumulate(x => x.ToString()));
}

And now the implementation:

using System;
using System.Collections.Generic;

public static class AccumulateExtensions
{
    public static IEnumerable<U> Accumulate<T, U>(this IEnumerable<T> collection, Func<T, U> func)
    {
        foreach (var curr in collection)
        {
            yield return func(curr);
        }
    }
}
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2018 April 12, 19:50