Check the null object with the LINQ statement.

Source: Internet
Author: User

The Page set function of blog writing today searches for pages based on URLs. The LINQ statement obtains the qualified page from the GetModelList () set of SitePage. If the Page fails to be queried, it jumps to the 404 page. The Code is as follows:

Var page = (from p in optSitePage. getModelList () where p. virtualUrlPath. toLower () = requestTitle. toLower () select p ). first (); if (null = page) {context. response. redirect ("/404.html"); return ;}

I intentionally passed a nonexistent URL. The result of the linq statement directly reports an error: System. InvalidOperationException: Sequence contains no elements. I checked MSDN and found that if First () is used, if there is no element in the result set, it will not return null. Change to FirstOrDefault.

? Var page = (from p in optSitePage. GetModelList () where p. VirtualUrlPath. ToLower () = requestTitle. ToLower () select p). FirstOrDefault ();

Traceback http://www.wyjexplorer.cn/Home/View/D44F795B009E20FD.html

 

From Wang Yujie

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.