Search code examples
c#arrayslistanonymousstoring-data

Store anonymous values in a list and extract each individually


I'm trying to store information in a block of anonymous values

//holds all info
var jobs = new { newJob, numBytes, requiredTime };

then take that information and place it into a list as a single element

//puts above info into a list
joblist.Add(Convert.ToString(jobs));
Console.WriteLine(joblist[0]);   //testing purposes

now what I would like to do is be able to call joblist and take the value of example numBytes at position 4.

Is this possible? Or could someone help with an alternate way of doing this? Much thanks!


Solution

  • The "normal" thing to do in C# would be to create a class to hold the information that you want to store. For example:

    public class Job
    {
        public string Name { get; set; }
        public int NumBytes { get; set; }
        public DateTime RequiredTime { get; set; }
    }
    

    Then you can add these to a list:

    var jobs = new List<Job>();
    
    var aJob = new Job();
    aJob.Name = "Job 1";
    aJob.NumBytes = 123;
    
    jobs.add(aJob);
    

    Then you can access jobs by its index in the list:

    var jobNumBytes = jobs[3].NumBytes;
    

    One thing to note about C#, when you do:

    new { newJob, numBytes, requiredTime };
    

    The compiler, at build time, just creates you a strongly typed class (just like the Job class I created above) and generates a random name for it. It infers the property names and types from the variables that you are assigning to it. The created .exe or .dll actually does contain a class definition for this type, you just can't easily get to it from other places in your code. It isn't truly "dynamic". So using that syntax is usually just a lazy way of declaring a class that you just need for a moment. Usually just inside 1 method, then you don't need it any more. Creating a named class is usually what you want to do.