c# - Linq to Excel 极慢

标签 c# excel linq-to-excel

我正在尝试创建一个应用程序,用于从自动生成的 excel 文件中提取一些数据。使用 Access 可以非常轻松地完成此操作,但文件位于 Excel 中,并且解决方案必须是一键式的东西。

出于某种原因,不执行任何操作而简单地循环遍历数据速度很慢。下面的代码是我尝试从慢得多的东西对其进行优化的尝试。在直接使用 Interop 类并通过不同的包装器进行了几次尝试后,我已经开始使用 Linq to SQL。

我还在此处和 Google 上阅读了一些问题的答案。为了找出导致速度缓慢的原因,我删除了所有说明,但保留了相关部分中的“i++”。它仍然很慢。我还尝试通过限制在第三行的 where 子句中检索的记录数来优化它,但这没有用。您的帮助将不胜感激。

谢谢。

        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 t 的查询放入括号中,然后在其上调用 ToList()。

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

由于 linq 的惰性/延迟执行模型,无论何时迭代集合,它都会重新查询数据源,除非您给它一个 List 来处理。

关于c# - Linq to Excel 极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18635752/

相关文章:

c# - 级联下拉列表数据源

c# - c#中类参数的模拟类

c# - 在 asp.net mvc 中检查上传的 Excel 文件中的非法字符

c# - header 中的 LinqToExcel 点

c# - 无法加载文件或程序集 'LinqToExcel,版本

c# - 你调用的对象是空的。 - 默认值

c# - 使用 Protobuf-net 反序列化二进制文件时线类型无效

Excel 在线自定义 URL 参数

Excel - 条件格式 - 单元格不为空且等于 0

python - 使用 python 创建与 excel 兼容的 CSV 文件?