Remove null fields from a model that receives a list

Asked

Viewed 60 times

2

I need to remove all null fields, which comes from a list of Phones, I tried to do it this way, but unfortunately it didn’t work:

model.Phones = model.Phones.Where(x => x.Phone != null && x.Phone != "")
                                          .Distinct()
                                          .ToList();

received the following error:

Nullreferenceexception: Object Reference not set to an instance of an Object.

Example: inserir a descrição da imagem aqui

  • It may seem like a stupid question, but the Nullreference error occurred using this image data?

  • Not exactly, this image I made with an example, but also generate the error. Where it generated the error instead of being {Konbase.Areas.Admin....} was null

  • In case that phone list is in memory or you bring it straight from the database?

  • Actually she comes from a form, i dynamically Gero fields of Telefones with BeginCollection, so the user can type as many phone fields as he wants, thus leaving inputs null if he doesn’t fill in all.

  • The command is correct. The error probably occurs by a model or the model.Phones null. Try to validate if null before using the command.

  • Your problem then is in sending the form, it should send "only" the phones that have values. But you can delete to be able to remove the values, something like this: "model.Phones.Remove(x => string.Isnullorempty(x.Phone)". With that should solve the problem.

Show 1 more comment

4 answers

1


I managed to solve,

If anyone needs an answer I did it this way:

model.Phones = model.Phones.Where(x => x != null && x.Phone != null).Distinct().ToList();

0

Try as follows, make sure your lista headphones have some value, and then run logic.

if(model.Phones.Count > 0)
 //coloque aqui sua logica

You can check if your phones are filled in too, before adding them in your list, follow example:

if(!string.IsNullOrEmpty(telefone))
  //adiciona telefone a lista
  • In fact, my problem is that as the fields that the user sends are dynamic inputs, example it can have only 1 phone input or 30, it depends on user and it can create the input and send it empty, this generates my problem.

0

Try something like this

model.Phones.RemoveAll(item => item == null);

Exchange the item as your need...

I put in the fiddle: https://dotnetfiddle.net/CVn50U

-1

If you received the Exception NullReferenceException, try the code below, sometimes the field Phones may be null.

if(model?.Phones?.Count > 0)
{
 model.Phones = model.Phones.Where(x => !string.IsNullOrEmpty(x.Phone)).Distinct().ToList();
}
  • I just tried this, but kept getting the error mexmo

  • Try again, I changed the IF config

Browser other questions tagged

You are not signed in. Login or sign up in order to post.