如何优化for循环...循环访问DataTable [英] how to optimize a for loop... looping through a DataTable

查看:256
本文介绍了如何优化for循环...循环访问DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中有以下循环:



dtPertdata是一个DataTable。



 for(int a = 0; a< dtPertdata.Rows.Count; a ++)
{
DataRow dr2 = dtPertdata.Rows [a];
if(a> = 10)
{
DataRow dr1 = dtPertdata.Rows [a - 10];
double rt2 = Convert.ToDouble(dr2 [value]);
double rt1 = Convert.ToDouble(dr1 [value]);

double shock10 = rt2 - rt1;
double pertYield = shock10 + Convert.ToDouble(dr2 [cur_yield]);

dr2 [shock10] = shock10.ToString();
dr2 [pertYield] = pertYield.ToString();
}
}
dtPertdata.AcceptChanges();







请建议如何在不使用循环的情况下进行此操作,例如使用linq或其他方法。

解决方案

没有什么可以优化的。 Linq本身并不比传统方法更具性能。它通常更紧凑,更快地并且更容易阅读。从理论上讲,可以用一些扩展方法语法编写代码,但它不会更快,因为它只会在引擎盖下执行相同的循环。在这种情况下(确定现有对象的新值),它不会更容易阅读,也几乎不会更紧凑。你的代码很好(如果它的工作方式应该如此)。


正如其他人已经注意到的那样,使用Linq会不会更快。它只隐藏它在内部使用的循环。



但是,有一个优化:

只需在索引10开始循环。 / BLOCKQUOTE>

I have the following loop in my program :

dtPertdata is a DataTable.

for (int a = 0; a < dtPertdata.Rows.Count; a++)
{
	DataRow dr2 = dtPertdata.Rows[a];
	if (a >= 10)
	{
		DataRow dr1 = dtPertdata.Rows[a - 10];
		double rt2 = Convert.ToDouble(dr2["value"]);
		double rt1 = Convert.ToDouble(dr1["value"]);

		double shock10 = rt2 - rt1;
		double pertYield = shock10 + Convert.ToDouble(dr2["cur_yield"]);

		dr2["shock10"] = shock10.ToString();
		dr2["pertYield"] = pertYield.ToString();		
	}	
}
dtPertdata.AcceptChanges();




Please suggest how to do this operation without using loop, for eg using linq or some other method.

解决方案

There is nothing to optimize. Linq is not inherently more performant than a "conventional" approach. It's just often more compact, faster to write and easier to read. Theoretically it would be possible to write your code in some extension method syntax but it would not be faster because it would just do the same loop "under the hoods". And in this case (assingning new values to an existing object) it would not be easier to read and also barely more compact. Your code is fine (if it works like it should).


As already noted by others using Linq would not be faster. It only hides the loops that it uses internally.

However, there is one optimisation:
Just start your loop at index 10.


这篇关于如何优化for循环...循环访问DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆