我正在使用麻省理工学院开发的LinqToExcel项目,并在http://code.google.com/p/linqtoexcel/wiki/UsingLinqToExcel上托管在Google代码上。
看起来非常直接和优雅。我能够重写一个使用MS excel互操作库的方法,代码大小只有1/3。
但是,我遇到了尝试查询一系列单元格的问题。 VS2008选择它作为语法错误:
//These lines are fine
IEnumerable<string> names = new List<string>();
var excel = new Excel.ExcelQueryFactory(_excelFilePath);
//This line shows a syntax error starting from c[0]
names = from c in excel.WorksheetRange("A1", "AI1", headerName)
c[0] == "IN"
select c;
线 - c [0] ==“IN” - 看起来很奇怪。这应该获取单元格A1中的值。如果我删除“c [0] == IN”语法错误消失,但它不返回任何结果。
这种语法是否正确?链接页面上的代码是C#?
更新:在得到一些答案后,似乎缺少“Where”确实是一个错字。然而,即使有“哪里”我也无法得到c [4] ==“IN”返回单元格A5。通过删除整个where子句,我能够完成我需要的操作,该子句返回了指定的整个范围。在最初的帖子中,我只想回归一个价值 - 宝贝步骤:)
为了标记答案 - 我将如何返回范围内的一个单元格?也许== "IN"
是某种拼写错误,而不是LinqToExcel的实际构造?
感谢您的帮助!
答案 0 :(得分:6)
应该是:
var names = from c in excel.WorksheetRange("A1", "AI1", headerName)
where c[0] == "IN"
select c;
答案 1 :(得分:2)
我认为你需要一个where
,它可能是文档页面上的拼写错误,你试过吗
//These lines are fine
//IEnumerable<string> names = new List<string>(); removed this as not really needed
var excel = new Excel.ExcelQueryFactory(_excelFilePath);
//This line shows a syntax error starting from c[0]
var names = from c in excel.WorksheetRange("A1", "AI1", headerName)
where c[0] == "IN"
select c;
编辑更新以添加var
也需要
答案 2 :(得分:2)
在该页面上,显示的查询中约有一半有where
,有一半没有。{我认为这只是一个'复制'错误。这不是LinqToExcel可以控制的语法的一部分。
但是,我注意到你说没有那行,就不会返回任何结果。这是另一个问题,因为如果没有那行,应该返回每一行(尽管如果我正确读取它,你的范围只有一行长)。但是,我假设LinqToExcel的工作方式与LinqToSql和LinkToObject类似,并且它是 lazy evaluate ,这意味着它在您实际执行之前不会执行查询。
另一点:
IEnumerable<string> names = new List<string>();
names = from c in excel.WorksheetRange("A1", "AI1", headerName)
where c[0] == "IN"
select c;
第一行创建一个字符串列表,然后在下一行抛弃。许多新的C#程序员似乎认为新的需要声明变量的类型,但是IEnumerable<string>
部分完全由此处理。 new
是不必要的。该行可以写成:
IEnumerable<string> names = null;
或只是
IEnumerable<string> names;
或者可以与第二行结合使用:
IEnumerable<string> names
= from c in excel.WorksheetRange("A1", "AI1", headerName)
where c[0] == "IN"
select c;
或缩写为:
var names = from c in excel.WorksheetRange("A1", "AI1", headerName)
where c[0] == "IN"
select c;
答案 3 :(得分:1)
试试这个:
//These lines are fine
IEnumerable<string> names = new List<string>();
var excel = new Excel.ExcelQueryFactory(_excelFilePath);
//This line shows a syntax error starting from c[0]
names = from c in excel.WorksheetRange("A1", "AI1", headerName)
where c[0] == "IN"
select c;
答案 4 :(得分:0)