[英]how to check the value for null in linq?
我有一个称为specifications
的表和一个列表字段,需要检查其值是否为空。 这是清单:
List<string> fieldList = new List<string>() { name1, name2, name3 }; //name of the fields
我已经尝试了以下方法:
var checkForNull = TableInfo.Get("specifications").Fields.Where(i => fieldList.Find(x=>x==null)))
但是它不会选择null
值。
如何检查该值,同时如何将该字段名称保存到新列表?
示例:我的列表中有3个名称(name1,name2,name3),数据库中的值是(name1 = 30,name2 = null,name3 = null)
因此,会将name2和name3添加到列表中。
所以我也尝试了:
TableInfo.Get("specifications").Fields.Where(i => fieldList .Contains(i.Name) && i.IsEmptyValue(i));
但这是行不通的。
如果要检查null或为空,请使用IsNullOrEmpty()方法:
string name1, name2, name3;
name1 = "test";
name2 = null;
name3 = null;
List<string> fieldList = new List<string>() { name1, name2, name3 }; //name of the fields
var nullOrEmptyElementes = fieldList.Where(e => string.IsNullOrEmpty(e)).ToList();
否则,您可以只检查空值:
var nullOrEmptyElementes = fieldList.Where(e => e==null).ToList();
使用ToList()方法,可以将IEnumerable <T>
“转换”为列表<T>
。
这条路:
class Program
{
static void Main(string[] args)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT name, value FROM specifications", connection))
{
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(result);
}
}
}
List<string> foundNullSpecifications = result.Rows.OfType<DataRow>().Select(x => new Specification
{
Name = (string)x["name"],
Value = x["value"]
}).Where(x => x.Value == null).Select(x => x.Name).ToList();
}
}
public class Specification
{
public string Name { get; set; }
public object Value { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.