开发者

Checking if a variable is empty c#

开发者 https://www.devze.com 2023-03-13 11:25 出处:网络
I have a pretty basic question but it is doing my nut in!!!! I have created a variable which checks my data table checks to see if an item using my page control ID already exists. IF it does I then w

I have a pretty basic question but it is doing my nut in!!!!

I have created a variable which checks my data table checks to see if an item using my page control ID already exists. IF it does I then want to warn my user that they have already chosen a page colour!

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

var qry = from x in db.DT_Control_ColourPalette_PageColors
                  wh开发者_运维技巧ere x.PageControlID == int.Parse(HF_CPID.Value)
                  select new
                  {
                      x.PageControlID,
                  };

The argument I think is right?

if (qry !=null)


Query expressions don't return null as far as I know. If there are no results you just get an IQueryable<T> with no Ts inside.

You can use this instead to see if there's anything in the result set:

if (qry.Any())


presuming that should return a single value - 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
}


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
}


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

If the result is both intended to be a single value and you're getting that from a single property, I have some comments.

  1. There's no reason to use an anonymous object to select a single value.
  2. If you find yourself wrapping a query-style statement in parenthesis to use the dot style on the result, you might consider just going to dot style.
  3. Choose between FirstOrDefault and SingleOrDefault depending on your data. Sometimes it's relevant to implicitly assert that the result is "one or nothing" versus "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

精彩评论

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