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#?
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With