将Datatable转换为ienumerable <anonymous>?</anonymous>

时间:2012-04-02 19:12:33

标签: c# collections ienumerable

是否可以在不知道其类名的情况下将数据表转换为ienumerable。

我的要求是转换表

First | Last
--------------
john  | mcgill
clara | linda   

{{First:john,Last:mcgill},{First:clara ,Last:linda}}

无法收集的

我不想使用动态对象,因为动态对象仅支持框架工作4。

谢谢

4 个答案:

答案 0 :(得分:8)

var results = from row in dataTable.AsEnumerable()
              select new {
                  First = row.Field<string>("First"),
                  Last = row.Field<string>("Second")
              };

您需要System.Data.DataSetExtensions

答案 1 :(得分:1)

您可以使用Anonymous Types - 它们是在.NET 3.5中引入的。

这种对象的语法非常清晰直观:

var item = new { First = "First-Value", Last = "Last-Value" }

和查询:

var items = dataTable.AsEnumerable()
                     .Select(i => new {
                                           First = i.Field<string>("First"),
                                           Last= i.Field<string>("Last")
                                      });

答案 2 :(得分:1)

请不要列名!

    public string ConvertDataTableToString(DataTable table)
    {
        int iColumnCount = table.Columns.Count;
        int iRowCount = table.Rows.Count;
        int iTempRowCount = 0;
        string strColumName = table.Columns[0].ColumnName;
        string strOut = "{";
        foreach (DataRow row in table.Rows) 
        {
            strOut = strOut + "{";
            foreach (DataColumn col in table.Columns)
            {
                string val = row.Field<string>(col.ColumnName);
                strOut = strOut + col.ColumnName + ":" + val;

                if (col.Ordinal != iColumnCount - 1)
                {
                    strOut = strOut + ",";
                }
            }
            strOut = strOut + "}";
            iTempRowCount++;

            if (iTempRowCount != iRowCount)
            {
                strOut = strOut + ",";
            }
        }
        strOut = strOut + "}";
        return strOut;
    }

答案 3 :(得分:0)

使用匿名类型是一项相当容易的工作。这是一个完整的示例,只需要System.Linq和System.Data命名空间中的类:

  class Program
  {
    static void Main(string[] args)
    {
      DataTable dataTable = new DataTable();
      dataTable.Columns.Add().ColumnName = "First";
      dataTable.Columns.Add().ColumnName = "Last";
      var row = dataTable.NewRow();
      row["First"] = "hello";
      row["Last"] = "world";
      dataTable.Rows.Add(row);

      var query = dataTable.Rows.Cast<DataRow>()
        .Select(r => new
        {
          First = r["First"],
          Last = r["Last"]
        });

      foreach (var item in query)
        Console.WriteLine("{0} {1}", item.First, item.Last);
    }
  }