c# - default values for IEnumerable collection when length is zero -
i have ienumerable
collection:
public ienumerable<config> getconfig(string cid, string name) { var raw = db.ap_getinfo(cid, name); foreach (var item in raw.tolist().where(x => x.name!= null)) { var x = raw.count(); yield return new config { name = item.name.tostring(), value = item.value.tostring(), }; } }
the problem facing if return length of 0 unable set attributes else, if have response of length 1 attributes set database, length 0 want set dfault value name
, value
.
a linq solution - returns default if there no items in enumerable using defaultifempty
:
public ienumerable<config> getconfig(string cid, string name) { return db.ap_getinfo(cid, name) .where(x => !string.isnullorempty(x.name)) .select(x => new config { name = x.name.tostring(), value = x.value.tostring(), }) .defaultifempty(new config { name = "defaultname", value = "defaultvalue" }); }
Comments
Post a Comment