List.Where( "string".Contains()) returns NULL in a LINQ Query

My Product class:

public class Product {
 public int Id { get; set; }
 public string NameEnglish { get; set; }
 public string NameItalian { get; set; }
}

My Language class:

public class Language{
  public int Id { get; set; }
  public string LanguageType { get; set; }
}

and I have a method which searches in Products using "Name" properties and returns List<Product>:

List<Product> GetProductsFromSearch(int languageId, string searchedData){
    var products = _contex.Products.ToList();
    switch(languageId) //LanguageId 1 = English , LangaugeId 2 = Italian
    {
       case 1:
            return products.Where(i=>i.NameEnglish.Contains(searchedData)).ToList();
       case 2:
            return products.Where(i=>i.NameItalian.Contains(searchedData)).ToList();
       default:
            return products;
    }
}

The problem is, some of the products "English" or "Italian" name fields are not assigned in Db yet, so those are null fields.

And program gives error "Object reference not set to an instance of an object".

So I added an extra control which is :

return products.Where(i=> !string.isNullOrEmpty(i.NameEnglish) && 

                          i.NameEnglish.Contains(searchedData)).ToList()

But still I got the same error. Could someone help please? I got confused, shouldn't it pass the null fields?

NOTE: I know I should filtering directly in _context.Products.Where(i=>i.NameEnglish.Contains(searchedData)).ToList(); but this is for my test purposes, I'm trying to use "Where", in a "List" type.

Id | NameEnglish | NameItalian
1  | Ball        | Palla
2  | Phone       | Telefono
3  | Tshirt      | NULL
4  | NULL        | Bicchiere

NOTE: I had 12 rows now I have 4. (It didn't changed the result but I've deleted for you to see my table clearly)

You can use a null conditional operator if all those items are indeed not null. It's cleaner than a null check, IMO:

products.Where(p => p.NameEnglish?.Contains(searchedData) == true);

Likewise for NameItalian.

Find an item in List by LINQ?, 2) Where will return all items which match your criteria, so you may get an IEnumerable with one element: IEnumerable<string> results = myList.Where(s� var items = list.Where(item => item == search); // or var items = from item in list where item == search select item; And don't forget to check the list for null in any of these cases. Or use (list ??

Try the following:

List<Product> GetProductsFromSearch(int languageId, string searchedData){
   if (string.IsNullOrEmpty(searchedData))
       return new List<Product>();

   var query = _contex.Products; 

    switch(languageId) //LanguageId 1 = English , LangaugeId 2 = Italian
    {
       case 1:
            query = query.Where(i=>i.NameEnglish.Contains(searchedData));
       case 2:
            query = query.Where(i=>i.NameItalian.Contains(searchedData));
    }

    return query.ToList();
}

If this raises an error, please provide the exact exception details and any inner exception. The above should work and when passed to EF2SQL it should handle the potential for the names to be null.

As you mention, you want to load from the List. In this case you would need to assert the null check:

List<Product> GetProductsFromSearch(int languageId, string searchedData){
   if (string.IsNullOrEmpty(searchedData))
       return new List<Product>();

   var query = _contex.Products.ToList(); 

    switch(languageId) //LanguageId 1 = English , LangaugeId 2 = Italian
    {
       case 1:
            query = query.Where(i=> !string.IsNullOrEmpty(i.NameEnglish) && i.NameEnglish.Contains(searchedData));
       case 2:
            query = query.Where(i=> !string.IsNullOrEmpty(i.NameItalian) && i.NameItalian.Contains(searchedData));
    }

    return query.ToList();
}

I suspect your attempt may have failed if you mistyped/copy-paste an issue with a null check against the wrong name value for a different language. I.e. IsNullOrEmpty against the English name but did the Contains on the Italian one.

Filtering data: the Where() method, As a result, we get a version of the original list, where we have only included numbers below 10, which is then outputted to the console. But the expression� LIST: Where to get a COVID-19 test in East Texas. CBS19 has compiled a list of local testing options that will be updated as new sites open. Author: Reagan Roy Published: 2:28 PM

Try i=>i.NameItalian != null && i.NameItalian.Contains(searchedData) and likewise for the English one.

SQL WHERE IN, SELECT WHERE IN List or Subquery, SQL WHERE IN Clause. What does SQL IN return? WHERE IN returns values that matches values in a list or subquery. WHERE IN is shorthand for multiple OR � Where. This is a keyword used inside queries. It is used in generic type constraints. And Where() is a method that filters elements from a collection.

I would recommend adding a logger to your context just for debugging purposes:

https://docs.microsoft.com/en-us/ef/ef6/fundamentals/logging-and-interception

You can then see what exact queries get generated and which exact query causes an issue. Sometimes the translation to sql doesn't work exactly like you think.

Sample LINQ Queries, IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, var teenStudentsName = from s in studentList where s.age > 12 && s.age� List definition is - a simple series of words or numerals (such as the names of persons or objects). How to use list in a sentence.

This comes down to a simple factor. You have to understand the flow of your assignment logic. NPEs always deal with variable asignments of which can be several reasons. Linq as a Any() which can be used to test a condition on a IEnumerable before having to pull its results. This may help you to device a proper handle for this exception.

How to find the index of list elements that meet a condition in Python, Use numpy.where(). Given a list of values and a condition, finding the index of elements meeting the condition returns a list of indices in the list where the� Mecklenburg County and Atrium Health are giving away 2 million free face masks to residents starting Friday. The full list of locations across the Charlotte area is below. “They decrease the

C# Where Method and Keyword, Use the Where extension method and the where keyword. </summary> class PageSet<T> where T : IPage { List<T> _pages = new List<T>(); public void Add(T � COLUMBIA, S.C. (WBTW) -- DHEC announced Thursday 1,636 new cases of COVID-19 and 48 new deaths, bringing the total number of cases to date to 87,117 and the total number of deaths to 1,599.

LIST, List::Where: Find where items are equal to a certain value. The result is a list containing only the values where the filter function returned a non-zero number� COVID-19 is spreading throughout East Texas and it's important to know where you can get tested. CBS19 has compiled a list of local testing options that we will continuously update as new sites open.

where - filtering values, main() { List languages = new List(); languages.add('Perl'); languages.add(' Python'); languages.add('Dart'); print(languages); // [Perl, Python, Dart] List short� Wikipedia (/ ˌ w ɪ k ɪ ˈ p iː d i ə / wik-ih-PEE-dee-ə or / ˌ w ɪ k i ˈ p iː d i ə / wik-ee-PEE-dee-ə; abbreviated as WP) is a multilingual online encyclopedia created and maintained as an open collaboration project by a community of volunteer editors using a wiki-based editing system.

Comments
  • There's no difference between your two 'case' statements.
  • Which line of code does the exception occur on? Also, please paste the exact code you are trying because string.isNullOrEmpty won't compile, it's string.IsNullOrEmpty It's hard to narrow down problems if you're trying to transcribe where you think the issue lies rather than providing the exact code.
  • @Sach the difference is i.NameEnglish vs i.NameItalian.
  • Oh OK. Just noticed.
  • I agree with @StevePy. That exception can result from a couple different lines here, so we need to know exactly which one is causing it
  • Trying immediately.
  • If you change both and still have an issue, something else is going on and it can't be these lines.
  • Okay Matt this worked, but what was the difference between "!= null , string.isNullOrEmpty(str) " and this one? Can you please explain?
  • Appears to be a lesser known behavior of LINQ: stackoverflow.com/a/772283/12431728 ... Short-circuit evaluation doesn't occur the way one may expect.
  • One other difference is if NameEnglish is empty and searchedData is empty then this will result in true while the IsNullOrEmpty should result in false.
  • OP said they added that check.
  • Yes I added this one and string.isNullOrEmpty checks
  • I didn't see the != null, only the string.IsNullOrEmpty() which are really different from the perspective of Entity Framework.
  • But this stuff isn't going to EF because they OP does a ToList before they apply the Where.
  • Thak you, I ll add.