문제

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;
        }

    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top