locked
LINQ : contains not checking with null values. RRS feed

  • Question

  • User-1024101449 posted

    Hi,

    I want to check some word which contains some + symbols. when i write the below query it should return true.

    but, i am getting object reference error.

    Also my condition is should check null value in column2 and column3

    below is my code:


    Inparam1 = "A+B";  
    bool Result1 = DT1.AsEnumerable()
                                   .Any(row => (row.Field<String>("Col1").contains(Inparam1)) && (row.Field<String>("col2") == null) && (row.Field<String>("col3") == null)));

    The above code should return "TRUE" as per my below referring table. But, it returns "Object reference Error"

    DT1 Table

    Col1 Col2 Col3
    A+B/D+EB    
    A/D+EB    
    A+B/X+A1    
    A 2 3

    what is the problem and where i want to change the code..?

    Wednesday, July 12, 2017 7:32 AM

Answers

  • User-1509636757 posted

    Debug and make sure that DT1 is not null. The query that you have posted working fine if DT1 has value that you have specified. Here is an example:

    {
        public partial class WebForm241 : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                DataTable DT1 = new DataTable();
                DT1.Columns.AddRange(new DataColumn[] { new DataColumn("Col1"), new DataColumn("Col2"), new DataColumn("Col3") });
                DT1.Rows.Add("A+B/D+EB", null, null);
                DT1.Rows.Add("A/D+EB", null, null);
                DT1.Rows.Add("A+B/X+A1", null, null);
                DT1.Rows.Add("A", "2", "3");
    
                string Inparam1 = "A+B";
                bool Result1 = DT1
                                .AsEnumerable()
                                .Any(row => (row.Field<String>("Col1").Contains(Inparam1)) && 
                                            (row.Field<String>("Col2") == null) && 
                                            (row.Field<String>("Col3") == null));
            }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 12, 2017 1:59 PM