如何不在 min 中包含空值

How not to include null values in min

我的表单中有一个 DataGridView,它有很多列。在其中四列中,我想使用 Min() 获得最低值。但是,有时有些列具有空值。当它尝试比较四个值时,我不希望包含 null。

问题是,如果其中一列为空,当我希望它达到 return 最低值时,它总是 return 空。有什么想法吗?

foreach (DataGridViewRow row in dgv_csv.Rows)
{
    mfn_new[i] = row.Cells[21].Value.ToString();
    mfn_used[i] = row.Cells[22].Value.ToString();
    fba_new[i] = row.Cells[23].Value.ToString();
    fba_used[i] = row.Cells[24].Value.ToString();

    var list = new[] { mfn_new[i], mfn_used[i], fba_new[i], fba_used[i] };
    string min = list.Min();
    MessageBox.Show(min);

    i++;
}
list.Where(item => item != null).Min()

但是为什么您将数字表示为 string?我假设您正在寻找 Min 个数字,而不是一个字符串 - 考虑更改类型

如果 .Valuenull,下面的行 mfn_new[i] = row.Cells[21].Value.ToString(); 可能会抛出 NullReferenceException,所以稍后检查它是否是 null不相关。


更新问题id后提示:

mfn_new[i] = row.Cells[21].Value?.ToString();
....

list.Where(item => item != string.Empty).Min()