Checking if a variable is empty C #

I have a pretty simple question, but it makes my nut in !!!!

I created a variable that checks my data tables to see if an element exists using the page control identifier. IF this is me, then I want to warn my user that they have already chosen the color of the page!

My question is how to check if this variable is empty or not!

var qry = from x in db.DT_Control_ColourPalette_PageColors where x.PageControlID == int.Parse(HF_CPID.Value) select new { x.PageControlID, }; 

An argument that I think is right?

 if (qry !=null) 
+6
source share
4 answers

Assuming one value needs to be returned - if so, then:

 var qry = (from x in db.DT_Control_ColourPalette_PageColors where x.PageControlID == int.Parse(HF_CPID.Value) select new { x.PageControlID, }).FirstOrDefault(); if(qry != null) { // do stuff } 
+6
source

Query expressions do not return null as far as I know. If there are no results, you just get an IQueryable<T> without T inside.

You can use this instead to find out if there is anything in the result set:

 if (qry.Any()) 
+16
source
 var qry = from x in db.DT_Control_ColourPalette_PageColors where x.PageControlID == CheckValue(HF_CPID.Value) select new { x.PageControlID, }; private int CheckValue(sting str) { if(!string.IsNullOrEmpty(str)) { return int.Parse(str); } else return 0;//or your default value you want to return } 
0
source

I was going to write this as an answer to another answer, but it is really too big for that. This is more or less an answer to Nathan's answer.

If the result of both is for the same value, and you get it from one property, I have some comments.

  • There is no reason to use an anonymous object to select a single value.
  • If you find that a query style operator is used in parentheses to use the dot style as a result, you might consider simply switching to a point style.
  • Choose FirstOrDefault and SingleOrDefault depending on your data. Sometimes this has to do with the implicit statement that the result is โ€œone or nothingโ€ compared to โ€œthe first of something or nothing.โ€
 var result = db.DT_Control_ColourPalette_PageColors .Where(x => x.PageControlID == int.Parse(HF_CPID.Value)) .Select(x => x.PageControlID) .SingleOrDefault(); if (result != null) { //... } 
0
source

Source: https://habr.com/ru/post/890744/


All Articles