-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

3
  • 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); Commented Mar 27, 2020 at 17:16
  • edit your question and include a minimal reproducible example. You could provide test data for _models_List Commented Mar 27, 2020 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 Commented Mar 27, 2020 at 17:21

1 Answer 1

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>();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.