加速DataTable非常耗时的方法

时间:2013-10-15 13:13:46

标签: sql c#-4.0

我正在研究一个解决方案,我有一个非常耗时的方法(GetArbeitsplaene),我不知道加速它。我的数据有一个SQL 2008 R2 Express Edition DB。在一个表中,我有100.000个条目。这是我的代码:

/// <summary>
/// Gets the arbeitsplaene.
/// </summary>
private void GetArbeitsplaene()
{
    DataColumn col = new DataColumn("Arbeitsplan", typeof(List<Arbeitsplan>));
    dTable.Columns.Add(col);

    for (int i = 0; i < dTable.Rows.Count; i++)
    {
        DataRow row = dTable.Rows[i];
        string materialnummer = Convert.ToString(row[1]);

        if (arbeitsplaeneTable == null)
        {
            SQLHelperClass.CreateTable(cn, "ARBEITSPLAENE", ref arbeitsplaeneTable);
        }

        DataRow[] select = arbeitsplaeneTable.Select("Material Like '" + materialnummer + "'");
        List<Arbeitsplan> list = Converter.ConvertDataRowToArbeitsplaene(select);

        dTable.Rows[i].SetField("Arbeitsplan", list);
    }

    // very important, otherwise the changes of the images will be tracked.
    dTable.AcceptChanges();
}

/// <summary>
/// Converts the data row to arbeitsplaene.
/// </summary>
/// <param name="select">The select.</param>
/// <returns></returns>
public static List<Arbeitsplan> ConvertDataRowToArbeitsplaene(DataRow[] select)
{
    List<Arbeitsplan> list = new List<Arbeitsplan>();

    for (int i = 0; i < select.Count(); i++)
    {
        Arbeitsplan plan = new Arbeitsplan();
        DataRow row = select[i];
        plan.Material = Convert.ToString(row[0]);
        plan.Vrg = Convert.ToString(row[1]);
        plan.Steu = Convert.ToString(row[2]);
        plan.Kurztext_Vorgang = Convert.ToString(row[3]);
        plan.Arbeitsplatz = Convert.ToString(row[4]);
        plan.LstArt = Convert.ToString(row[5]);
        plan.Kostenstelle = Convert.ToString(row[6]);
        list.Add(plan);
    }

    return list;
}

    /// <summary>
    /// Creates the table.
    /// </summary>
    /// <param name="tableName">Name of the table.</param>
    /// <param name="table">The table.</param>
    public static void CreateTable(SqlConnection cn, string tableName, ref DataTable table)
    {
        string sql = "select * from " + tableName;
        SqlCommand cmd = new SqlCommand(sql, cn);
        SqlDataAdapter tempAdapter = new SqlDataAdapter(cmd);
        SqlCommandBuilder tempcb = new SqlCommandBuilder();
        tempcb.ConflictOption = ConflictOption.OverwriteChanges;
        tempcb.DataAdapter = tempAdapter;
        table = new DataTable();
        tempAdapter.Fill(table);
    }

所以我需要运行for循环100.000次,这需要时间。如何才能更快地改进代码?

谢谢, TRO

0 个答案:

没有答案