2

I have a class:

    public class ChartData
    {        
      public Decimal? Value { get; set; }        
      public DateTime Date { get; set; }        
    }

And I have also

    List<List<ChartData>> chartData = List<List<ChartData>>();

chartData can contains any number of List, it could be one, but also it could be ten lists.

I need this structure flattened. For example if I have two lists in chartData I need to get list of objects where each object contains fields:

    {
      Decimal? Value0
      Decimal? Value1
      DateTime Date
    }

if I have ten lists I need to get list of objects where each object contains fields:

    {
      Decimal? Value0
      Decimal? Value1
      .
      .
      .
      Decimal? Value9
      DateTime Date
    }

Is it possible to do it using linq or other C# functions?

Thanks in advance.

  • Are you sure this is right: `public Decimal? Value { get; set; }`? How is that "any number of List"? Is it supposed to be `public IList Values { get; set; }` or something like that? – Jon B Nov 27 '12 at 14:29

2 Answers2

3

If chartData can really contain any number of lists, you are out of luck, since you cannot dynamically create fields in a .NET class. The exact structure of a class must be known at compile time, even if it is an anonymous class.

You might consider using

{
    List<Decimal?> Values,
    DateTime Date
}

or

{
    Decimal?[] Values,
    DateTime Date
}

instead, which can both be created easily via LINQ. If you elaborate on why you need them to be separate fields (Maybe some kind of serialization requirement? If yes, which format?), the SO community might be able to suggest an alternative solution. In addition, you should specify which Date value should be used, if they differ.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

You can use the dynamic possibilities of C# introduced in version 4.0.

See this SO article on property bags.

Note however, that you lose any compiletime checks! Consider it twice, before you do that.

Community
  • 1
  • 1
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188