Wednesday 6 June 2018

Create Dynamic Object on the fly in C#

Many times we required Object on the fly, at run time. On that case
System.Dynamic.ExpandoObject and Newtonsoft.Json.Linq.JObject
will help us more.


In the below example you can see how we can extract few data on the fly from a Type having all properties. This dynamic object example may help us developing web api where we need list.


Example:


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Dynamic_Objects
{
    class Program
    {
 
        string GetCityAsJson()
        {
            City objCity = new City();
            var cities = objCity.GetAllCities().Select(o =>
            {
                dynamic city = new System.Dynamic.ExpandoObject();
                city.Text = o.Name;
                city.Value = o.ID;
                return city;
            }
            ).ToList();
 
            return JsonConvert.SerializeObject(cities);
        }
 
 
        string GetCityAsJson2()
        {
 
            City objCity = new City();
            var cities = objCity.GetAllCities().Select(o =>
            {
                dynamic city = new Newtonsoft.Json.Linq.JObject();
                city.Text = o.Name;
                city.Value = o.ID;
                return city;
            }
            ).ToList();
 
            return JsonConvert.SerializeObject(cities);
        }
 
 
        string GetCityAsJson3()
        {
 
            City objCity = new City();
            var cities = objCity.GetAllCities().Select(o =>
            new
            {
                Text = o.Name,
                Value = o.ID
            }
            ).ToList();
 
            return JsonConvert.SerializeObject(cities);
        }
 
        static void Main(string[] args)
        {
            Program obj = new Program();
            Console.WriteLine(obj.GetCityAsJson());
            Console.WriteLine("---------------------------------------");
            Console.WriteLine(obj.GetCityAsJson2());
 
            Console.Read();
        }
    }
 
 
 
    class City
    {
        public int ID { getset; }
        public string Name { getset; }
        public string PreviousName { getset; }
        public string ShortName { getset; }
        public decimal longitude { getset; }
        public decimal latitude { getset; }
 
        public List<City> GetAllCities() =>
            new List<City>(){
                new City() { ID= 1, Name = "New Delhi", PreviousName="Delhi", ShortName = "Del", latitude= 24.40m, longitude= 77.14m   },
                new City() { ID= 1, Name = "Tokyo", PreviousName="Tokyo", ShortName = "Tok", latitude= 35.40m, longitude= 139.45m   }
            };
 
    }
}