Initialize a Jagged Array the LINQ Way

后端 未结 6 2190
孤城傲影
孤城傲影 2020-12-14 04:07

I have a 2-dimensional jagged array (though it\'s always rectangular), which I initialize using the traditional loop:

var myArr = new double[rowCount][];
for         


        
6条回答
  •  再見小時候
    2020-12-14 04:43

    You can't do that with the Repeat method : the element parameter is only evaluated once, so indeed it always repeats the same instance. Instead, you could create a method to do what you want, which would take a lambda instead of a value :

        public static IEnumerable Sequence(Func generator, int count)
        {
            for (int i = 0; i < count; i++)
            {
                yield return generator();
            }
        }
    
        ...
    
        var myArr = Sequence(() => new double[colCount], rowCount).ToArray();
    

提交回复
热议问题