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 T
s 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.
- There's no reason to use an anonymous object to select a single value.
- 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.
- Choose between
FirstOrDefault
andSingleOrDefault
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)
{
//...
}
精彩评论