c# - 数据表通过 linq 将零替换为 null 或空字符串

标签 c# linq datatable

我有一个数据表,其中包含一些带 0 的值。现在我想用 null 或 ""替换所有的 0。

示例数据表

A       B       C
6       0       7
0       7       0
5       0       4

预期

A       B       C
6               7
        7        
5               4

我可以通过 for 循环来完成,但是可以通过 LINQ 来完成吗?

最佳答案

你必须做这样的事情。

 //I am constructing a data table here. You already have this I guess.
        var dataTable = new DataTable();
        dataTable.Columns.Add(new DataColumn("A", typeof(int)) { AllowDBNull = true });
        dataTable.Columns.Add(new DataColumn("B", typeof(int)) { AllowDBNull = true });
        dataTable.Columns.Add(new DataColumn("C", typeof(int)) { AllowDBNull = true });

//Assign values
        DataRow row1 = dataTable.NewRow();
        row1["A"] = 6;
        row1["B"] = 0;
        row1["C"] = 7;
        dataTable.Rows.Add(row1);

        DataRow row2 = dataTable.NewRow();
        row2["A"] = 0;
        row2["B"] = 7;
        row2["C"] = 0;
        dataTable.Rows.Add(row2);

        DataRow row3 = dataTable.NewRow();
        row3["A"] = 5;
        row3["B"] = 0;
        row3["C"] = 4;
        dataTable.Rows.Add(row3);

//This is what you need.
        foreach (DataRow row in dataTable.Rows)
        {
            if ((int)row["A"] == 0)
            {
                row["A"] = DBNull.Value;
            } 
            if ((int) row["B"] == 0)
            {
                row["B"] = DBNull.Value;
            }
            if ((int) row["C"] == 0)
            {
                row["C"] = DBNull.Value;
            }
        }

//test the changes
        foreach (DataRow row in dataTable.Rows)
        {
            Console.WriteLine("" + row["A"] + "; " + row["B"] + "; " + row["C"]);
        }

关于c# - 数据表通过 linq 将零替换为 null 或空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34689282/

相关文章:

c# - 分片目录结构算法

c# - Union 或 Concat 中的类型不能用层次结构构造

c# - Linq AddRange() 用于从接口(interface)派生的对象

c# - Linq 查询数据集中的多个数据表

c# - 如何使用 EPPLUS 从 Excel 电子表格单元格中获取值?

c# - 安装好vs2015后如何在vs2015上安装Asp.Net?

c# - 如何将经过身份验证的用户更改为 Google Drive API

c# - 加速嵌套 for 循环并提高性能

c# - MVC4 - Linq Lambda 表达式查询多个关联表

javascript - 从数据表中删除 dataTable 类