0

So I'm really trying to build dynamic reports in C# based off of multiple stored procedures across multiple databases and then join the results.

Here is an example:

List 1:

  { monthyear = '032016', submitted = '56', approved = '27'},
  { monthyear = '042016', submitted = '67', approved = '30'}

List 2

  { monthyear = '032016', returned = '17'},
  { monthyear = '042016', returned = '22'}

Knowing that the "key" column is dynamic and the results built into each list are dynamic. I am however able to retrieve a string representation of the key column that joins the lists.

The result I am looking for is:

  { monthyear = '032016', submitted = '56', approved = '27', returned = '17'},
  { monthyear = '042016', submitted = '67', approved = '30', returned = '22'}

Both list are stored as an IEnumerable<object> with an intended result of IEnumerable<object>.

Is there a way to join these, not concat, without looping?

duckmike
  • 1,006
  • 4
  • 16
  • 39

2 Answers2

2

in linq you can write the join query as this

var res = list1.Join(list2, a => a.monthyear , b => b.monthyear ,
(a, b) => new { a.monthyear,a.returned, b.submitted, b.approved});

but i`m not sure how it is implemented internally

Edit

in this case you`ll need to use reflection first (you can enhance this)

foreach (PropertyInfo p in typeof(firstObj).GetProperties())
        {
            foreach (PropertyInfo p2 in typeof(secondObject).GetProperties())
                if (p.Name == p2.Name)
                    match = p.Name;
        }

now the variable match stores the key as string

list1.Join(list2, a=>a.GetType().GetProperty(match).GetValue(a,null), b => b.GetType().GetProperty(match).GetValue(b,null), (a, b) => new { a.first, a.second..... });

or

, (a,b) => new { a, b});

my guide was this and this

morever check this to select all the properties if you don`t know their names

hope this helps

Community
  • 1
  • 1
Modar Na
  • 873
  • 7
  • 18
0

Well, looping is going to be required, if for no other reason than to loop through the SP results as they come in from the database.

That aside, you could have a Dictionary<string, Dictionary<string, object>> that will hold the final result. Reflection can pull all properties out from each of the records as they come in, and drop them into a Dictionary<string, object> for each record (keyed by property name, value is property value). Then merge these dictionaries into the big Dictionary<string, Dictionary<string, object>> which is keyed by whatever property you're interested in (looks like the "monthyear" property).

Reflection might not even be necessary e.g. if you're using a DataTable then you already have programmatic access to all the record field names and values.

Matt Thomas
  • 5,279
  • 4
  • 27
  • 59