I building the following anonymous object:
var obj = new {
Country = countryVal,
City = cityVal,
Keyword = key,
Page = page
};
I want to include members in object only if its value is present.
For example if cityVal
is null, I don't want to add City in object initialization
var obj = new {
Country = countryVal,
City = cityVal, //ignore this if cityVal is null
Keyword = key,
Page = page
};
Is this possible in C#?
Its not even posibble with codedom or reflection, So you can end up doing if-else if you really need this
if (string.IsNullOrEmpty(cityVal)) {
var obj = new {
Country = countryVal,
Keyword = key,
Page = page
};
// do something
return obj;
} else {
var obj = new {
Country = countryVal,
City = cityVal,
Keyword = key,
Page = page
};
//do something
return obj;
}
You can't do that.
But what you could do is provide the default value (null?) of those properties.
var obj= new
{
Country= countryVal,
City = condition ? cityVal : null,
Keyword = condition ? key : null,
Page = condition ? page : null
};
Well you would have if else conditions. But, if you are serilizing this as a JSON object with newtonsoft JSON this could help:
var json = JsonConvert.SerializeObject(value, Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
You could use an ExpandoObject and a functional extension method.
pubic class SomeClass
public dynamic DomainFunction(
object countryVal = null
, object cityVal = null
, object key = null
, object page = null
)
{
dynamic obj = new ExpandoObject();
cityVal?.Tee(x => obj.City = x);
countryVal?.Tee(x => obj.Country = x);
key?.Tee(x => obj.Keyword = x);
page?.Tee(x => obj.Page = x);
return obj;
}
}
public static class FunctionalExtensionMethods{
public static T Tee<T>(this T source, Action<T> action)
{
if (action == null)
throw new ArgumentNullException(nameof (action));
action(source);
return source;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.