如何从数据库中获取特定列的所有值

How to get all values from database for a particular column

我有一家公司 table 并且我使用了查询 select * from company 。但是现在我只需要这个 table 中的所有公司名称,如何获取并存储到字符串 array.Following 代码片段只有我得到的公司名称的原始代码。但是如何获取所有公司名称并存储到数组中

reader = cmd.ExecuteReader();

            // write each record
            while(reader.Read())
            {
                Console.WriteLine("{0}", 
                    reader["CompanyName"]; 

            }

不确定您是否需要专门在一个数组中,或者只是一个集合...但是您可以执行以下操作:

reader = cmd.ExecuteReader();

List<string> listOfCompanyNames = new List<string>();

        // write each record
        while(reader.Read())
        {
            Console.WriteLine("{0}", 
                reader["CompanyName"]; 
            listOfCompanyNames.Add(reader["CompanyName"]);
        }

        var arrayOfCompanyNames = listOfCompanyNames.ToArray();

请注意,您需要导入 System.Collections.GenericSystem.Linq

选项 1:使用 ArrayList

ArrayList dynamically resizes. As elements are added,and space is needed, it grows in capacity. It is most often used in older C# programs.

ArrayList companylist = new ArrayList();

reader = cmd.ExecuteReader();

// write each record
while(reader.Read())
 {
    companylist.Add(reader["CompanyName"]);
 }

foreach (var name in companylist)
{ 
   Console.WriteLine(name);
}

选项 2:使用列表

Replacement for deprecated ArrayList.

List<string> companylist = new List<string>();

reader = cmd.ExecuteReader();

// write each record
while(reader.Read())
 {
    companylist.Add(reader["CompanyName"]);
 }

foreach (var name in companylist)
{ 
   Console.WriteLine(name);
}

//Converting list to string Array
var CompanyNamesArray = companylist.ToArray();