我可以使用 DataAdapter C# 填充列表吗
假设我有这段代码(伪代码),
class SomeClass
{
class Person
{
public static string Name { get; set; }
public static int Age { get; set; }
}
List<Person> person = new List<person>;
public void SelectPerson()
{
DataTable dt = new DataTable();
SqlConnection conn = GetConnection();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT name, age FROM person", conn);
da.Fill(dt);
}
}
我可以根据 DataAdapter 的结果填充列表(人员)吗? 我该怎么做呢?或者有什么解决方法吗?谢谢...
Suppose I have this code (pseudocode)
class SomeClass
{
class Person
{
public static string Name { get; set; }
public static int Age { get; set; }
}
List<Person> person = new List<person>;
public void SelectPerson()
{
DataTable dt = new DataTable();
SqlConnection conn = GetConnection();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT name, age FROM person", conn);
da.Fill(dt);
}
}
Can I fill the List (person) based on the result of my DataAdapter?
How should I do it? Or is there any workaround? Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
最好的方法可能是不要先读入数据表:
警告:您想快速关闭 DataReader/连接,不要进行大量处理。上面的代码比使用 DataTable 作为中介更有效。
但是,如果您确实想首先使用数据表,则可以使用 LINQ:
或只是迭代 dt.Rows 并创建一个新人员并将其添加到列表中
您还应该使用 Using() statements 围绕您的 连接和阅读器。
Probably the best way is not to read into a datatable first:
Caveat: You want to close the DataReader/connection quickly, don't do lots of processing. The above code is more efficient than using a DataTable as an intermediary.
But if you do want to use a data table first, you could use LINQ:
or just itterate of dt.Rows and create a new person and add it to the list
You should also use Using() statements around your connection and reader.
还有 Linq to DataSet,你可以用它来做一些事情,
罗伯特比我先找到了答案,只是使用了稍微不同的语法。
There's also Linq to DataSet that you could use to do something along these lines
Robert beat me to the answer, just using slightly different syntax.
除了提供的其他选项之外,您还可以使用收益将执行推迟到需要时:
In addition to the other options presented, you could defer the execution until needed with a yield:
首先,您需要使您的“名称”和“年龄”字段成为非静态的(因此该类的每个实例都将拥有自己的这些属性值。
然后您可以执行以下操作:
希望这会有所帮助!
First, you'll want to make your Name and Age fields non-static (so each instance of the class will have their own values for these properties.
Then you could do something like this:
Hope this helps!
是的,你可以。迭代
dt.Rows
中的项目并将它们手动转换为Person
对象。Yes you can. Iterate through the items in
dt.Rows
and convert them manually toPerson
objects.最近,一位用户问我一个关于将 DataTable 转换为 List<> 的问题。在.NET 2.0 中。这是执行此操作的代码:
C#
A user recently asked me a question on converting a DataTable to a List<> in .NET 2.0. Here’s the code to do so:
C#