极其缓慢的Linq到Excel

我试图创build一个应用程序,将自动生成的Excel文件中提取一些数据。 这可以很容易地与Access完成,但文件在Excel中,解决scheme必须是一个button的事情。

出于某种原因,仅仅循环数据而不做任何动作是很慢的。 下面的代码是我尝试从慢得多的东西来优化它。 我经过几次尝试直接使用Interop类,并通过不同的包装来使用Linq to SQL。

我也在这里和谷歌阅读了几个问题的答案。 为了查看是什么导致缓慢,我已经删除了所有的说明,但保留“i ++”的相关部分。 这还是很慢的。 我也尝试通过限制在第三行的where子句中检索到的logging数来优化它,但是这不起作用。 你的帮助将不胜感激。

谢谢。

Dictionary<string,double> instructors = new Dictionary<string,double>(); var t = from c in excel.Worksheet("Course_201410_M1") // where c["COURSE CODE"].ToString().Substring(0,4) == "COSC" || c["COURSE CODE"].ToString().Substring(0,3) == "COEN" || c["COURSE CODE"].ToString().Substring(0,3) == "GEIT" || c["COURSE CODE"].ToString().Substring(0,3) == "ITAP" || c["COURSE CODE"] == "PRPL 0012" || c["COURSE CODE"] == "ASSE 4311" || c["COURSE CODE"] == "GEEN 2312" || c["COURSE CODE"] == "ITLB 1311" select c; HashSet<string> uniqueForce = new HashSet<string>(); foreach (var c in t) { if(uniqueForce.Add(c["Instructor"])) instructors.Add(c["Instructor"],0.0); } foreach (string name in instructors.Keys) { var y = from d in t where d["Instructor"] == name select d; int i = 1; foreach(var z in y) { //this is the really slow. It takes a couple of minutes to finish. The // file has less than a 1000 records. i++; } } 

将形成var的查询放入括号中,然后调用ToList()。

  var t = (from c in excel.Worksheet("Course_201410_M1") select c).ToList(); 

由于linq的延迟/延迟执行模型,每当迭代集合时,它将重新查询数据源,除非您给它一个List来处理。