我可以使用 DataAdapter C# 填充列表吗

发布于 2024-10-15 22:55:29 字数 548 浏览 1 评论 0原文

假设我有这段代码(伪代码),

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

街角卖回忆 2024-10-22 22:55:29

最好的方法可能是不要先读入数据表:

var dr = new DataReader(....) // Fill in what is needed, can't remember offhand
while(dr.Next())
{
    persons.Add(
        new Person() {
            Name = (string) r["Name"], 
            Age = (int) r["Age"] 
        }
    );
}

警告:您想快速关闭 DataReader/连接,不要进行大量处理。上面的代码比使用 DataTable 作为中介更有效。

但是,如果您确实想首先使用数据表,则可以使用 LINQ:

var list = dt.AsEnumerable().Select(r => new Person() { 
    Name = (string) r["Name"], 
    Age = (int) r["Age"] }
).ToList()

或只是迭代 dt.Rows 并创建一个新人员并将其添加到列表中

您还应该使用 Using() statements 围绕您的 连接和阅读器

Probably the best way is not to read into a datatable first:

var dr = new DataReader(....) // Fill in what is needed, can't remember offhand
while(dr.Next())
{
    persons.Add(
        new Person() {
            Name = (string) r["Name"], 
            Age = (int) r["Age"] 
        }
    );
}

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:

var list = dt.AsEnumerable().Select(r => new Person() { 
    Name = (string) r["Name"], 
    Age = (int) r["Age"] }
).ToList()

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.

习惯成性 2024-10-22 22:55:29

还有 Linq to DataSet,你可以用它来做一些事情,

var list = (from tr in dt.AsEnumerable()
    select new Person() { 
        Name = tr.Field<string>("Name"), 
        Age = tr.Field<int>("Age") 
    }).ToList();

罗伯特比我先找到了答案,只是使用了稍微不同的语法。

There's also Linq to DataSet that you could use to do something along these lines

var list = (from tr in dt.AsEnumerable()
    select new Person() { 
        Name = tr.Field<string>("Name"), 
        Age = tr.Field<int>("Age") 
    }).ToList();

Robert beat me to the answer, just using slightly different syntax.

拧巴小姐 2024-10-22 22:55:29

除了提供的其他选项之外,您还可以使用收益将执行推迟到需要时:

public static IEnumerable<Person> GetPeople()
{
    using( var conn = GetConnection() )
    {
        conn.Open();
        string sql = "SELECT name, age FROM person";
        var cmd = new SqlCommand( sql, conn );

        using( SqlDataReader rdr = cmd.ExecuteReader() )
        {
            if( rdr == null )
            {
                throw new NullReferenceException( "No People Available." );
            }
            while( rdr.Read() )
            {
                var person = new Person();
                person.Name = rdr["name"].ToString();
                person.Age = Convert.ToInt32 ( rdr["age"] );

                yield return person;
            }           
        }
    }
}

In addition to the other options presented, you could defer the execution until needed with a yield:

public static IEnumerable<Person> GetPeople()
{
    using( var conn = GetConnection() )
    {
        conn.Open();
        string sql = "SELECT name, age FROM person";
        var cmd = new SqlCommand( sql, conn );

        using( SqlDataReader rdr = cmd.ExecuteReader() )
        {
            if( rdr == null )
            {
                throw new NullReferenceException( "No People Available." );
            }
            while( rdr.Read() )
            {
                var person = new Person();
                person.Name = rdr["name"].ToString();
                person.Age = Convert.ToInt32 ( rdr["age"] );

                yield return person;
            }           
        }
    }
}
眼泪都笑了 2024-10-22 22:55:29

首先,您需要使您的“名称”和“年龄”字段成为非静态的(因此该类的每​​个实例都将拥有自己的这些属性值。

然后您可以执行以下操作:

foreach(DataRow row in dt.Rows){
    Person p = new Person(){
        Name = Convert.ToString(row["name"]),
        Age = Convert.ToInt32(row["age"])
    }
    person.Add(p);
}

希望这会有所帮助!

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:

foreach(DataRow row in dt.Rows){
    Person p = new Person(){
        Name = Convert.ToString(row["name"]),
        Age = Convert.ToInt32(row["age"])
    }
    person.Add(p);
}

Hope this helps!

北音执念 2024-10-22 22:55:29

是的,你可以。迭代dt.Rows中的项目并将它们手动转换为Person对象。

Yes you can. Iterate through the items in dt.Rows and convert them manually to Person objects.

孤寂小茶 2024-10-22 22:55:29

最近,一位用户问我一个关于将 DataTable 转换为 List<> 的问题。在.NET 2.0 中。这是执行此操作的代码:

C#

// Assuming there is a DataTable called dt

List<DataRow> drlist = new List<DataRow>();

foreach (DataRow row in dt.Rows)
{
    drlist.Add((DataRow)row);
}

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#

// Assuming there is a DataTable called dt

List<DataRow> drlist = new List<DataRow>();

foreach (DataRow row in dt.Rows)
{
    drlist.Add((DataRow)row);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文