Reputation: 10805
bool isExist = objCustomization.CustomSettings.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID).Any();
if (isExist)
{
chkFixLimit.Checked = objCustomization.CustomSettings.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID).FirstOrDefault().IsDefaultLimit;
}
else chkFixLimit.Checked = false;
Upvotes: 2
Views: 74
Reputation: 75306
This not in one line but it is more readable, you can change:
var setting = objCustomization.CustomSettings
.FirstOrDefault(p => p.CustomizationType == selCustomizationType
&& p.CategoryID == selCategoryID);
chkFixLimit.Checked = setting == null ? false : setting.IsDefaultLimit;
Upvotes: 2
Reputation: 12226
chkFixLimit.Checked = objCustomization.CustomSettings
.Where(p => p.CustomizationType == selCustomizationType
&& p.CategoryID == selCategoryID)
.Select(c => c.IsDefaultLimit)
.FirstOrDefault();
Upvotes: 2
Reputation: 236218
Default value for boolean is false
so you even don't need any conditions - just select first or default IsDefaultLimit
value:
chkFixLimit.Checked =
objCustomization.CustomSettings
.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID)
.Select(p => p.IsDefaultLimit)
.FirstOrDefault();
UPDATE (answer for your comment) in case you have non-boolean value or default value (zero for integer) do not fit your requirements, with DefaultIfEmpty you can provide own default value if there is no items matching your condition:
maxCountCmb.SelectedIndex =
objCustomization.CustomSettings
.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID)
.Select(p => p.DefaultFreeCount)
.DefaultIfEmpty(-1)
.First();
Upvotes: 5
Reputation: 125630
Sure you can:
var item = objCustomization.CustomSettings.FirstOrDefault(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID);
chkFixLimit.Checked = item != null && item.IsDefaultLimit;
Or single statement, as you wish:
chkFixLimit.Checked = new Func<bool>(() => {
var item = objCustomization.CustomSettings.FirstOrDefault(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID);
return item != null && item.IsDefaultLimit;
}).Invoke();
Upvotes: 3
Reputation: 30892
That code is more-or-less the use case of the FirstOrDefault
method. If something exists, return the first such item, and return a default value (null
for reference types) if it doesn't. So you could just do:
var item = objCustomization.CustomSettings.FirstOrDefault
(p => p.CustomizationType == selCustomizationType && p.CategoryID)
and as result, the item
object will either be null
(assuming you indeed work with a reference type), or it will have a value.
After that you can just check that, with a simple
chkFixLimit.Checked = (item == null) ? false : item.IsDefaultLimit;
Upvotes: 1