将数据表/数据视图中的所有数据转换为大写/小写

问题描述 投票:0回答:1

我想将所有数据(即数据表或数据视图中的数据列的所有行)转换为相同的大小写,即大写或小写,以便无论大小写如何我都可以找出重复项。

我有很少的列是动态生成的,所以我不能通过给出列名来做到这一点

我有这样的数据

c# asp.net datatable dataview
1个回答
0
投票

您可以为 DataTable 创建一个扩展方法,它可以使用 DataTable 以及大写/小写布尔标志。下面的代码可以帮助您实现所需的输出。

public static class DataTableExtensions
{
    public static void NormalizeCase(this DataTable table, bool toUpperCase = true)
    {
        if (table == null)
            throw new ArgumentNullException(nameof(table));

        foreach (DataRow row in table.Rows)
        {
            foreach (DataColumn column in table.Columns)
            {
                var cellValue = row[column];

                if (cellValue != null && cellValue != DBNull.Value)
                {
                    string stringValue = cellValue.ToString();

                    if (toUpperCase)
                    {
                        stringValue = stringValue.ToUpper();
                    }
                    else
                    {
                        stringValue = stringValue.ToLower();
                    }

                    row[column] = stringValue;
                }
            }
        }
    }
}

如果答案对您有用,请投票。

© www.soinside.com 2019 - 2024. All rights reserved.