C # Conditional anonymous member objects in object initialization

I create the following anonymous object:

var obj = new { Country = countryVal, City = cityVal, Keyword = key, Page = page }; 

I want to include members in an object only if its value is present.

For example, if cityVal is null, I do not want to add City to the object initialization

 var obj = new { Country = countryVal,   City = cityVal,   // ignore this if cityVal is null 
     Keyword = key,
     Page = page
 };

Is this possible in C #?

+8
source share
4 answers

It's not even possible with a coded or reflection, so you can end up doing it if you really need it

 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; } 
+3
source

You cannot do this.

But what you can do is provide a default value (null?) Of these properties.

 var obj= new { Country= countryVal, City = condition ? cityVal : null, Keyword = condition ? key : null, Page = condition ? page : null }; 
+1
source

Well, you would have if more conditions. But, if you serialize this as a JSON object using newtonsoft JSON, this may help:

  var json = JsonConvert.SerializeObject(value, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); 
0
source

You can use ExpandoObject and the 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; } } 
0
source

Source: https://habr.com/ru/post/1485039/


All Articles