Linq:有什么具体的方法来运行查询?
我想知道是否我有一个Excel文件,我试图通过LINQ查询获取数据,这将是可行的?
Excel文件格式
+-----------------+-------------+ | Inputlocation | Inputvalue | +-----------------+-------------+ | 1 | Hello | +-----------------+-------------+ | 2 | World!!! | +-----------------+-------------+
现在,如果我使用下面给出的Linq查询,可能会得到Inputvalue数据
var fileName = @"C:\Users\jshah\Documents\Visual Studio 2013\Projects\QA_ExpScript\QA_ExpScript\Excel\Inputdata.xls"; string sheetName = "Input"; var book = new LinqToExcel.ExcelQueryFactory(fileName); var users = from x in book.Worksheet(Input) select x; foreach (var x in users) { Console.WriteLine(x["1"]); }
我想在这里做的是inputlocation是“1”给我inputvalue是“你好”。 我正确的方式来指定查询? 此外,我在我的代码中一次又一次地使用它。 所以请给这个更好的解决scheme。
您可以使用where
子句来过滤数据,如下所示: –
var users = from x in book.Worksheet() where x["Inputlocation"].Cast<int>() == 1 select x["Inputvalue"].Cast<string>();
那么你可以简单地遍历users
:
foreach (var item in users) { Console.WriteLine(item.Inputvalue); //This will print "Hello" }
尽pipe恕我直言,它总是更好地创build一个匹配types,以避免在指定列名时可能发生错别字的任何exception。
public class User { public int Inputlocation { get; set; } public string Inputvalue { get; set; } }
这里是查询: –
var users = from x in book.Worksheet<User>() where x.Inputlocation == 1 select x;
这跟我所做的有点相似,但有些回答这个问题。 但是不要说@RahulSingh在说什么。
在代码中也涉及@Chris 1。 而这个职位的创造者是我认为他不想改变他的职能anythhing。 他想要的唯一改变是Console.WriteLine(x["1"]);
或Console.WriteLine(x["2"]);
得到Inputvalue
参考我的文章