Lambda expression with AND operator in lambda expression

12,136

Solution 1

You can't use ToString() in LINQ method, but you can try this:

string selectedItem = listBox1.SelectedItem.ToString();
CUSTOMER customer = db.CUSTOMERs.First(p => (p.CUSTOMERID == idValoare) && (p.ADRESA.Equals(selectedItem)));

I hope that helps you. Please feedback.

Solution 2

It looks like your listbox1 doesn't have a selected item. You should really add an extra conditional to perform that check before you do any of your code.

Simply:

if (listbox1.SelectedItem == null)
{
    //get the hell out of here
}
else
{
   //do your stuff
}
Share:
12,136
Bogdan
Author by

Bogdan

Updated on June 05, 2022

Comments

  • Bogdan
    Bogdan almost 2 years

    I get an error (

    Object reference not set to an instance of an object

    ) when i try to do the database operation, i can't seem to find what's wrong, must be something from this p.ADRESA.Equals(listBox1.SelectedItem.ToString() because without it the code works but i need two conditions, please help

     Int16 idValoare =Convert.ToInt16 (comboBoxIDValoare.SelectedItem.ToString());
    
            if (selectedTabel.Equals("CUSTOMER"))
            {
                if (selectedColoana.Equals("ADRESA"))
                {
                    CUSTOMER customer = db.CUSTOMERs.First(p => (p.CUSTOMERID == idValoare) && (p.ADRESA.Equals(listBox1.SelectedItem.ToString())));
                    customer.ADRESA = textBoxValoare.Text;
                    db.SaveChanges();
                }
    }
    
  • Bogdan
    Bogdan about 11 years
    I checked the SelectedItem is not null :|
  • Bogdan
    Bogdan about 11 years
    at this line CUSTOMER customer = db.CUSTOMERs.First(p => (p.CUSTOMERID == idValoare) && (p.ADRESA.Equals(listBox1.SelectedItem.ToString())));
  • Bogdan
    Bogdan about 11 years
    CUSTOMER customer = db.CUSTOMERs.First(p => (p.CUSTOMERID == idValoare)); works fine
  • mattytommo
    mattytommo about 11 years
    Can ADRESA be null in your database?
  • Bogdan
    Bogdan about 11 years
    in debugger it says : An unhandled exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll Additional information: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
  • Silvermind
    Silvermind about 11 years
    @guNNer2bad You could put it into a (string) variable first and use that variable in your expression.