如何从列表中删除空然后添加
问题描述:
我有一个正在从我的数据库表中填充的列表,我正在尝试稍后在代码中进行转换。我无法进行转换,因为程序读取的是空值,并表示这是非法操作,所以我认为在将它们添加到列表之前排除空值可能是我的最佳选择。我知道有很多类似的帖子,但我已经尝试了其中几个没有运气。这是列表oldNames。我试过oldNames = oldNames.Where(m => !string.IsNullOrEmpty(m)).ToList();
, oldNames.RemoveAll(string.IsNullOrWhiteSpace);
, oldNames.Where(i => i != null).ToList().Add(actualPDF);
但是我需要从他们那里得到一个计数,所有这三个返回0的计数为for (int i = 0; i < oldNames.Count; i++)
。任何帮助将不胜感激,谢谢!如何从列表中删除空然后添加
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
}
}
答
如果目的是从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);
}
+0
完美!谢谢 – rychrist88
什么是实际'NULL'在这里?如果存在来自数据库的不希望选择的NULL值,那么可以用SQL WHERE someColumn IS NOT NULL之类的东西排除它们。 – David
您能澄清最后一条语句(关于需要获取计数)?你是否说排除所有空值后列表为空?是否有任何非空值被添加到列表中? – Jacob
我会尝试你说的@David,看看它是否适合我。雅各布没有任何东西被添加到列表中,但是当我使用上面代码中看到的原始方式时,所有值都被添加到列表中,包括空值 – rychrist88