0

DataTable/Datagridview の特定の列のすべての値が DateTime または数値であるかどうかを確認するための高速な方法が存在するかどうかを知るために、あなたの助けを求めています。

DGV の任意の列に特定の形式を配置するための一般的な方法を作成しようとしています。

以前にデータ型が定義されていない TEXT ファイル / Excel または XML ファイルからの情報があります

ありがとう!

4

1 に答える 1

1

ループを拡張メソッドに埋め込むことができます。ただし、ループが Linq 操作内に隠されている場合でも、最終結果にはどこかにループが必要になります。たとえば、次の拡張メソッドを記述できます。

public static void ApplyColumnFormatting(this System.Data.DataTable table, string column, Action formatDateTime, Action formatNumeric)
{
    bool foundNonDateTime = false;
    bool foundNonNumeric = false;

    DateTime dt;
    Double num;

    foreach (System.Data.DataRow row in table.Rows)
    {
        string val = row[column] as string;

        // Optionally skip this iteration if the value is not a string, depending on your needs.
        if (val == null)
            continue;

        // Check for non-DateTime, but only if we haven't already ruled it out
        if (!foundNonDateTime && !DateTime.TryParse(val, out dt))
            foundNonDateTime = true;

        // Check for non-Numeric, but only if we haven't already ruled it out
        if (!foundNonNumeric && !Double.TryParse(val, out num))
            foundNonNumeric = true;

        // Leave loop if we've already ruled out both types
        if (foundNonDateTime && foundNonNumeric)
            break;
    }

    if (!foundNonDateTime)
        formatDateTime();
    else if (!foundNonNumeric)
        formatNumeric();
}

次に、次のように呼び出すことができます。

System.Data.DataTable table = ...;

table.ApplyColumnFormatting("Column_Name",
    () => { /* Apply DateTime formatting here */ },
    () => { /* Apply Numeric formatting here */ }
);

これは、必要以上の行をチェックしないという意味で高速であり、特定のタイプが除外された後もチェックを続行しません。

于 2013-09-12T03:54:38.337 に答える