gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:24:01 24 4
gpt4 key购买 nike

我有一个数据表,其中包含一些带 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com