【问题标题】:how to check the value for null in linq?如何在linq中检查null的值?
【发布时间】:2019-04-24 07:10:08
【问题描述】:

我有一个名为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));

但这不起作用。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    如果要检查 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&lt;T&gt;“转换”为 List&lt;T&gt;。

    【讨论】:

    • 我看到了这个i.imgur.com/o2jh5HC.png,但信息管理器应该显示为“name2,name3”。怎么解决?
    • 请检查您正在使用的库。它应该是 System.Collections.Generic,而不是“filt2System”。为什么会这样显示?你是根据智能感知的建议创建的吗?
    • 我使用的是 System.Linq,我使用的是 resharper(
    • 什么是 tmsVisibleChr?你能把那行上面的代码发给我吗?
    【解决方案2】:

    这边:

    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; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2011-08-25
      • 2022-09-23
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多