簡體   English   中英

有沒有更有效的方法在 C# 中創建我的 DataTable?

[英]Is there a more efficient way to create my DataTable in C#?

我的項目中有一個簡單的 CreateDataTable 方法,這對我來說似乎有點笨拙且效率低下。 它有效,但有沒有更整潔的方式來寫這個?

private static DataTable CreateDataTable()
{

    var table = new DataTable("FileUploads");

    var id = new DataColumn
    {
        DataType = Type.GetType("System.Int32"),
        ColumnName = "Id",
        AutoIncrement = true,
        Unique = true
    };
    table.Columns.Add(id);

    var name = new DataColumn
    {
        DataType = Type.GetType("System.String"),
        ColumnName = "FileName",
        AutoIncrement = false,
        Caption = "FileName",
        ReadOnly = false,
        Unique = false
    };
    table.Columns.Add(name);

    var path = new DataColumn
    {
        DataType = Type.GetType("System.String"),
        ColumnName = "FilePath",
        AutoIncrement = false,
        Caption = "FilePath",
        ReadOnly = false,
        Unique = false
    };

//several more column inserts...

    var primaryKeyColumns = new DataColumn[1];
    primaryKeyColumns[0] = table.Columns["Id"];
    table.PrimaryKey = primaryKeyColumns;

    return table;

}

你可以做幾件事......

您可以忽略您設置為默認值的值,並為列名和類型使用構造函數參數以減少代碼使用。 我還將使用typeof(string)而不是Type.GetType("System.String")來提供編譯時錯誤而不是運行時錯誤。

添加列時使用AddRange並內聯創建它們。

擺脫冗長的主鍵內容並使用簡單的數組分配

這將使您獲得更少的代碼,因此出錯的可能性也更少。

private static DataTable CreateDataTable()
{
    var table = new DataTable("FileUploads");

    table.Columns.AddRange(new[]{
        new DataColumn("Id", typeof(int))
        {
            AutoIncrement = true,
            Unique = true
        },
        new DataColumn("FileName", typeof(string)),
        new DataColumn("FilePath", typeof(string)),
        // more columns here
    });

    table.PrimaryKey = new []{ table.Columns["id"] };

    return table;
}

我也去掉了Caption因為如果沒有設置,它默認為列名;)

這不那么冗長,也應該更容易閱讀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM