【问题标题】:Best practice when converting DataColumn values to an array of strings?将 DataColumn 值转换为字符串数组时的最佳实践?
【发布时间】:2010-01-16 14:25:28
【问题描述】:

将 DataColumn 值转换为字符串数组时的最佳实践?

[编辑] 将所有 DataTable 行的特定 DataColumn 的所有值转换为字符串数组?

【问题讨论】:

  • 你能指定吗?任何 Datarow 都有 ItemArray 属性,它以与为其定义的列相同的顺序返回一个对象数组。将对象转换为字符串就像在每个值上调用 ToString() 一样简单,但也许它是你想要的其他东西......
  • 要转换为字符串数组的 DataColumn 的值,但我正在寻找实现这一点的最佳方法。

标签: c# arrays string datatable


【解决方案1】:

如果我理解您的目标,您想指定一个特定列并将其所有值作为字符串数组返回。

试试这些方法:

int columnIndex = 2; // desired column index

// for loop approach        
string[] results = new string[dt.Rows.Count];
for (int index = 0; index < dt.Rows.Count; index++)
{
    results[index] = dt.Rows[index][columnIndex].ToString();
}

// LINQ
var result = dt.Rows.Cast<DataRow>()
                    .Select(row => row[columnIndex].ToString())
                    .ToArray();

您可以将columnIndex 替换为columnName,例如:

string columnName = "OrderId";"

编辑:您专门要求提供一个字符串数组,但如果您对要求很灵活,我更喜欢List&lt;string&gt;,以避免在第一个示例中的 for 循环并简单地向其中添加项目。这也是使用 foreach 循环代替的好机会。

然后我会重写代码如下:

List<string> list = new List<string>();
foreach (DataRow row in dt.Rows)
{
    list.Add(row[columnIndex].ToString());
}

【讨论】:

    【解决方案2】:

    【讨论】:

    • DataRow.ItemArray 将一行中的所有值作为数组返回。我认为 OP 希望将列中的所有值作为一个数组。也许您可以扩展您的答案以帮助解释 DataRow.ItemArrayDataTableExtensions 类如何提供帮助?
    【解决方案3】:

    我知道这个问题很老,但我在 Google 搜索中发现它试图做类似的事情。我想从我的数据表的特定行中包含的所有值创建一个列表。在下面的代码示例中,我使用 GUI 向导在 Visual Studio 中的项目中添加了一个 SQL 数据源,并将所需的表适配器放入设计器中。

    'Create a private DataTable
    Private authTable As New qmgmtDataSet.AuthoritiesDataTable
    
    'Fill the private table using the table adapter 
    Me.AuthoritiesTableAdapter1.Fill(Me.authTable)
    
    'Make the list of values
    Dim authNames As List(Of String) = New List(Of String)(From value As qmgmtDataSet.AuthoritiesRow In Me.authTable.Rows Select names.authName)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 2020-01-14
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 2014-06-21
      相关资源
      最近更新 更多