按索引访问DataTable列

时间:2013-12-26 18:19:32

标签: c#

我之前提出这个问题非常糟糕。让我从MSDN参考文章中澄清一下:

private void PrintValues(DataTable table)           
{           
    foreach(DataRow row in table.Rows)          
    {           
        foreach(DataColumn column in table.Columns)         
        {           
            Console.WriteLine(row[column]);
            -->I'd like to reference 'column' by index so I can map to my List<Record>records object.
        }
    }
}

我需要将DataTable对象转换为我自己的包含三个字段的Record类。最直接的方法似乎是通过索引获取相应的DataColumns,但我不确定是否可能?我能找到的唯一例子是'foreach'。

public class Record 
{   
    private string nameFormal;
    private string nameInternal;
    private string nameSpecial;     
}

Record sqlsGet() //return Record from DataTable
{
    //Connection c
    //DataAdapter a
    //DataTable t

    Record records = new Record();
    foreach(DataRow row in t.Rows)
    {
        foreach(DataColumn column in t.Columns)
        {
        //I'd like to do this:
            //records(row[0]).nameFormal;
        //records(row[1]).nameInternal;
        //records(row[2]).nameSpecial;
        }
    }
    return records
}

3 个答案:

答案 0 :(得分:2)

DataTable包含多行,因此您可能会获得List<Record>Record[]数组而不是单个记录。

List<Record> sqlsGet()
{
    var records = new List<Record>();
    foreach(DataRow row in t.Rows)
    {
        var record = new Record();
        record.nameFormal = row[0];
        record.nameInternal = row[1];
        record.nameSpecial = row[2];
        records.Add(record);
    }
    return records;
}

如您所见,您无需使用第二个t.Columns迭代foreach

如果您只需要返回一个Record,则必须从DataTable中选择一行。

Record sqlsGet()
{
    var record = new Record();

    // pick one row
    var row = t.Rows[0];

    record.nameFormal = row[0];
    record.nameInternal = row[1];
    record.nameSpecial = row[2];

    return record;
}

答案 1 :(得分:0)

由于您的返回类型为Record而非Record,我假设只有1行,因此只有1 List<Record>

Record record = new Record();
var row = t.Rows[0];
record.nameFormal = row[0];
record.nameInternal = row[1];
record.NameSpecial = row[2];

return record;

如果要返回记录列表,请使用循环:

List<Record> records = new List<Record>();
foreach(var row in t.Rows)
{
    Record record = new Record();
    record.nameFormal = row[0];
    record.nameInternal = row[1];
    record.NameSpecial = row[2];
    records.Add(record);
}
return records;

答案 2 :(得分:0)

您可以迭代DataTable中的每一行,并使用LINQ填充Record个对象列表:

List<Record> recordList
  = t.Rows.Cast<DataRow>().Select(x =>
     new Record { nameFormal = x[0], nameInternal = x[1], nameSpecial = x[2] });