使用 LINQ 从 DataTable 获取数据
我有一个数据表,我想将表的内容打印到控制台。
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("FName");
dt.Columns.Add("LName");
DataRow dr;
dr = dt.NewRow();
dr["FName"] = "FName1";
dr["LName"] = "LName1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["FName"] = "FName2";
dr["LName"] = "LName2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["FName"] = "FName3";
dr["LName"] = "LName3";
dt.Rows.Add(dr);
我希望在控制台上输出如下所示:
Row 1: FNAme = Fname1, LName = LName1
Row 2: FNAme = Fname2, LName = LName2
Row 2: FNAme = Fname3, LName = LName3
How can i do this using LINQ?
I have a datatable and i want to print the content of the table to console.
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("FName");
dt.Columns.Add("LName");
DataRow dr;
dr = dt.NewRow();
dr["FName"] = "FName1";
dr["LName"] = "LName1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["FName"] = "FName2";
dr["LName"] = "LName2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["FName"] = "FName3";
dr["LName"] = "LName3";
dt.Rows.Add(dr);
I want output on console like this:
Row 1: FNAme = Fname1, LName = LName1
Row 2: FNAme = Fname2, LName = LName2
Row 2: FNAme = Fname3, LName = LName3
How can i do this using LINQ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这与 LINQ 无关,您需要迭代这些项目。
This has nothing to do with
LINQ
, you will need to iterate over the items.这并不是 LINQ 的真正目的,但如果你真的想要......
This isn't really the purpose of LINQ but if you really want...
因此,您可以使用 LINQ 并编写类似的内容
但是对于您正在做的事情,
foreach
循环更有意义我说 foreach 循环更有意义的原因是它更清楚您在做什么。实现更简单。
LINQ 很棒,但我尝试只在它能更清晰地表示我正在做的事情时才使用它。老实说,它正在成为与处理集合的任何代码有关的任何事情的事实上的答案,但有时它并不是答案。
So you could use LINQ and write something like this
But for what you're doing a
foreach
loop makes more senseThe reason that I say that a foreach loop makes more sense is that it's clearer what you are doing. The implementation is simpler.
LINQ is great, but I try to only use it when it provides a clearer representation of what I am doing. It's honestly becoming the defacto answer for any thing to do with any code dealing with collections and sometimes it isn't the answer.
一个更通用的解决方案(也使用一些 LINQ,因为您似乎很喜欢它;-))
A more generic solution (also using some LINQ, since you seem to have the hots for it ;-))