我有一个从我的数据库表中填充的列表,我正在尝试稍后在代码中进行转换。我无法进行转换,因为程序读取空值并说它是非法操作,所以我想在将它们添加到列表之前排除空值可能是我的最佳选择。我知道有很多类似的帖子,但我尝试过其中一些没有运气。这是列表oldNames。我试过了oldNames = oldNames.Where(m => !string.IsNullOrEmpty(m)).ToList();
,
oldNames.RemoveAll(string.IsNullOrWhiteSpace);
,
oldNames.Where(i => i != null).ToList().Add(actualPDF);
但是我需要稍后从他们那里得到一个计数,并且所有这三个人都为计数for (int i = 0; i < oldNames.Count; i++)
返回0。任何帮助将不胜感激,谢谢!
List<string> oldNames = new List<string>(); //<----
public Form1()
{
InitializeComponent();
SqlConnection con = new SqlConnection(@"Data Source=x; Initial Catalog=x; Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM x", con);
DataTable dt = new DataTable();
sda.Fill(dt);
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.RootFolder = Environment.SpecialFolder.Desktop;
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtFileLocation.Text = fbd.SelectedPath;
}
string[] files = Directory.GetFiles(txtFileLocation.Text, "*.*", SearchOption.AllDirectories);
foreach (string val in files)
{
listBox2.Items.Add(Path.GetFileName(val));
}
foreach (DataRow row in dt.Rows)
{
var actualPDF = row["x"].ToString();
var namedFN = row["y"].ToString();
var fileID = row["z"].ToString();
var filesinFolder = listBox2.Items.ToString();
listBox1.Items.Add(fileID);
listBox4.Items.Add(namedFN);
oldNames.Add(actualPDF); // <--- This List
}
}
答案 0 :(得分:1)
如果目的是从row["x"]
检索非空项的计数,则对数据库执行查询:
select count(*) from [table] where x is not null
否则,从x中排除原始查询中为空的值:
select x, y, z from [table] where x is not null
或者,在对数据行执行任何操作之前,foreach循环应检查DBNull:
foreach (DataRow row in dt.Rows)
{
if(row["x"] == DBNull.Value || string.IsNullOrWhiteSpace(row["x"].ToString())
{
continue;
}
var actualPDF = row["x"].ToString();
var namedFN = row["y"].ToString();
var fileID = row["z"].ToString();
var filesinFolder = listBox2.Items.ToString();
listBox1.Items.Add(fileID);
listBox4.Items.Add(namedFN);
oldNames.Add(actualPDF);
}