相关疑难解决方法(0)

关于使用Enumerable.Range与传统for循环的foreach的思考

在C#3.0中,我喜欢这种风格:

// Write the numbers 1 thru 7
foreach (int index in Enumerable.Range( 1, 7 ))
{
    Console.WriteLine(index);
}
Run Code Online (Sandbox Code Playgroud)

在传统的for循环:

// Write the numbers 1 thru 7
for (int index = 1; index <= 7; index++)
{
    Console.WriteLine( index );
}
Run Code Online (Sandbox Code Playgroud)

假设'n'很小,所以性能不是问题,是否有人反对传统风格的新风格?

.net c# for-loop c#-3.0

64
推荐指数
12
解决办法
4万
查看次数

为什么Enumerable.Range比直接yield循环更快?

下面的代码是检查执行相同解决方案的三种不同方式的性能.

    public static void Main(string[] args)
    {
        // for loop
        {
            Stopwatch sw = Stopwatch.StartNew();

            int accumulator = 0;
            for (int i = 1; i <= 100000000; ++i)
            {
                accumulator += i;
            }

            sw.Stop();

            Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, accumulator);
        }

        //Enumerable.Range
        {
            Stopwatch sw = Stopwatch.StartNew();

            var ret = Enumerable.Range(1, 100000000).Aggregate(0, (accumulator, n) => accumulator + n);

            sw.Stop();
            Console.WriteLine("time = {0}; result = {1}", sw.ElapsedMilliseconds, ret);
        }

        //self-made IEnumerable<int>
        {
            Stopwatch sw = Stopwatch.StartNew();

            var ret = …
Run Code Online (Sandbox Code Playgroud)

c# performance ienumerable range enumerable

11
推荐指数
2
解决办法
6503
查看次数

使用公式将项目添加到数组的更快方法

我有这个代码块

double[] tabHeight = { 16, 10, 15, 20 };
double[] tabMidSectionWA = { 6, 2, 5, 6 };

double[] tabCurveWA = {
           (tabHeight[0] - tabMidSectionWA[0]) / 2 ,
           (tabHeight[1] - tabMidSectionWA[1]) / 2,
           (tabHeight[2] - tabMidSectionWA[2]) / 2 ,
           (tabHeight[3] - tabMidSectionWA[3]) / 2 
};
Run Code Online (Sandbox Code Playgroud)

是否有(tabheight - tabMid) / 2使用 for 循环或 foreach的公式添加这些值的更简单方法?

c#

-1
推荐指数
1
解决办法
90
查看次数

标签 统计

c# ×3

.net ×1

c#-3.0 ×1

enumerable ×1

for-loop ×1

ienumerable ×1

performance ×1

range ×1