0

I have the following model in my asp mvc application

 public class StringIntType
 {

    public string str { get; set; }
    public int nbr { get; set; }
    public string par { get; set; }
    public DateTime date { get; set; }
}

I run this query

  var sql = "select object as str , host as par from table " +
            "where date > '2015-01-01' and date <'2015-01-03' option (recompile)";

and map results into this list

var myList = (List<StringIntType>)db.Database.SqlQuery<StringIntType>(sql).ToList();

The problem is when i try to do some sorting in myList that way

 int n = myList.Where(x => x.par.Contains("object")).Count();

I get the following error

Object reference not set to an instance of an object at  x.par.Contains("object")
4
  • probably your myList is null thats why. Perform a null check before directly manipulating it Commented Apr 22, 2015 at 7:03
  • 2
    Looks like x.par is null Commented Apr 22, 2015 at 7:03
  • Provided myList is not null, may be there are rows in your table with 'par' column set to null? Commented Apr 22, 2015 at 7:04
  • @JPG that was it some columns are null i should add where columns not null Commented Apr 22, 2015 at 7:09

3 Answers 3

5

cause x.par can be null

So you can do like this:

int n = myList.Where(x => x.par != null && x.par.Contains("object")).Count();
Sign up to request clarification or add additional context in comments.

Comments

3

Try setting each x.par to a default value other than null or do a check on x.par for null before calling Contains on it.

Comments

2

x or x.par might be null :

int n = myList.Where(x => x != null &&  x.par != null && x.par.Contains("object")).Count();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.