.Net相当于Swift map并减少

时间:2018-01-12 10:20:32

标签: c# swift xamarin

我得到了这个操作:

let lines = (0..<linesCount).map({ _ in "\n" }).reduce("", +)

lineCount是一个整数。

如何将此代码转换为C#?

我写了Enumerable.Range(1, linesCount).Select(...)链接到.Aggregate(...)的内容,但我不知道要放入什么(...)以获得与Swift完全相同的结果线。

2 个答案:

答案 0 :(得分:4)

请尝试以下代码:

var linesCount = 4;
var lines = Enumerable
    .Range(1, linesCount)
    .Select(i => "\n")
    .Aggregate((c, n) => $"{c}{n}");

但是,如果您只需要创建一个重复多次的单个字符串,则可以使用string构造函数:

var lines = new string('\n', linesCount);

答案 1 :(得分:0)

MapReduce in C#

用C#映射

static void Main(string[] args)
{
   var testList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   var mapList = Map<int, int>(x => x + 2, testList);

   mapList.ToList<int>().ForEach(i => Console.Write(i + " "));
   Console.WriteLine();
   Console.ReadKey();
}

static IEnumerable<TResult> Map<T, TResult>(Func<T,TResult> func, 
IEnumerable<T> list)
{     
    foreach (var i in list)
       yield return func(i);
}

减少C#

static void Main(string[] args)
{
   var testList = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
   Console.WriteLine(Reduce<int, int>((x, y) => x + y, testList, 0));
   Console.ReadKey();
}

static T Reduce<T, U>(Func<U, T, T> func, IEnumerable<U> list, T acc)
{
   foreach (var i in list)
       acc = func(i, acc);

   return acc;
}