-1

I have a problem How can I inquire in a linq correctly Get a mistake NullReferenceException every time

    public class Model
    {
        public int Nmb { get; set; }
        public string _UserId { get; set; }
    }
    public static List<Model> _models_List { get; set; }

        string user = "test name";

        int test = _models_List.Where(o => o._UserId == user).Select(o => o.Nmb).DefaultIfEmpty(0).First();

        if (test == 0)
        {         
            Model obj = new Model();
            obj._UserId = user;
            obj.Nmb = 1;
            _models_List.Add(obj);
        }

I tried to correct the code like this But I get the same mistake NullReferenceException Value cannot be empty. Parameter name: Source

    int test = _models_List.Where(o => o._UserId == user).Select(o => o.Nmb).FirstOrDefault();

Please Help

hasan81
  • 27
  • 1
  • 4
  • `string _UserId = _models_List.Where(o => o._UserId == user).Select(o => o._UserId).FirstOrDefault();`, can be replaced with `var userExists = _models_List.Any(o => o._UserId == user);` – Igor Mar 27 '20 at 17:16
  • [edit] your question and include a [mcve]. You could provide test data for `_models_List` – Igor Mar 27 '20 at 17:19
  • Thanks for your response, sir you are right But I just want to know how to inquire the correct in linq, so I attached this example – hasan81 Mar 27 '20 at 17:21

1 Answers1

2

The list _models_List is empty, to solve the issue replace the following code:

public static List<Model> _models_List { get; set; }

with:

public static List<Model> _models_List { get; set; } = new List<Model>();
Alireza Mahmoudi
  • 964
  • 8
  • 35