Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
CSharp /
20180412cSelect (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 }
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); } } } |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |