Change datatype of an item of an object in a collection

Viewed 48

I am able to change the datatype of a particular property of an object on the fly, but I am not super happy with my approach, as I know that the object I am going to use in my project has like two dozen properties in there.

What I attempted

 class Program
    {
        static void Main(string[] args)
        {
            NammaClass nammaClass = new NammaClass();

            List<NammaClass> listNamma = new List<NammaClass>
            {
                new NammaClass{quant= 1, dattim = "01/01/2020"},
                new NammaClass{quant= 2, dattim = "02/02/2022"}
            };

            var newList = (from user in listNamma
                           select new
                           {
                               quant = user.quant,//I Don't want to write this
                               dattim = DateTime.Parse(user.dattim)
                           }).ToList();
        }
    }

    public class NammaClass
    {
        public int quant;
        public string dattim;
    }

The problem with above approach is that I am forced to use all the properties of the NammaClass object just to be able to change the datatype of one property, is there an elegant way to have the whole object but just one property's datatype changed.

1 Answers

If you're using C# 9 or later, you can use Records and the with expression:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record#nondestructive-mutation

If you need to copy an instance with some modifications, you can use a with expression to achieve nondestructive mutation. A with expression makes a new record instance that is a copy of an existing record instance, with specified properties and fields modified.

Example:

var newList = listNamma.Select(x => x with { dattim = DateTime.Parse(x.dattim) });

Related