开发者

Problem checking if any words in a list contain a partial string .net

I'm using C# .net and I'm getting NullReferenceException at this point:

Request.Params.AllKeys.Any(l => l.Contains("stringImLookingFor"));

used this on debug and "stringImLookingFor" is a constant (so is never null):

var aux = Request; 
var aux2 = Request.开发者_开发百科Params; 
var aux3 = Request.Params.AllKeys; 

And none of this was null. I guess the problem is because l.Contains("stringImLookingFor") returns null. Any idea how to fix it??

Thx.


Your error is because one of the following is null:

  • Request
  • Request.Params
  • Request.Params.AllKeys
  • l (used at l.Contains(). This would occur if you'd managed to get a null key in there somehow)

You can't tell which from the single liner though. Either stick on a breakpoint and check them manually, or add a check in code to see if each is null.

Update:

Would recommend

Request.Params.AllKeys.Any(l => !String.IsNullOrEmpty(l) &&
                           l.Contains("stringImLookingFor"));


Are you sure Request.Params or "stringImLookingFor" (if it's a variable, not constant) is not null?


I found the problem. Thx to @Ian!

I had a null key on Request.Params.AllKeys. By now my solution is:

List ParamsList = Request.Params.AllKeys.Where(l => !string.IsNullOrEmpty(l)).ToList();

ParamsList.Any(l => l.Contains("CourseName"))

If anyone finds something nicer, tell me please : )


Your second solution could potentially be very inefficient.

List ParamsList = Request.Params.AllKeys.Where(l => !string.IsNullOrEmpty(l)).ToList();
ParamsList.Any(l => l.Contains("CourseName"));

The above requires iterating over the entire collection to produce a new list, and then iterating over that new list until you find the element that matches. The below should be a little better:

Request.Params.AllKeys
    .Where(l => !string.IsNullOrEmpty(l))
    .Any(l => l.Contains("CourseName");

That will filter our any null values before it hits the call to Any. It will also mean that there is only one iteration through the collection, and will stop as soon as the course is found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜