0

My code receives an anonymous object created by another method. I would like to access and iterate through the nested collection in this object. I was trying to come up with several different ways to cast it using the 'as' keyword but no avail.

Here is the code which creates the object:

            var result = new object();
            foreach (var item in items)
            {
                result = new
                {
                    Variants = item.Value.Select(m => m.Item2).GroupBy(n => n.Item1).Select(r => new
                    {
                        Name = r.Key,
                        Items = r.Select(p => new
                        {
                            Value = p.Item2.Trim(),
                            Text = p.Item2.Substring(0, p.Item2.LastIndexOf('_')).Trim()
                        }).Where(p => !string.IsNullOrEmpty(p.Text)).ToList()
                    })
                };
            }

Visual Studio gives me the following signature when I hover over the variable which received this anonymous type:

{ Variants = {System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Linq.IGrouping<string, System.Tuple<string, string>>, <>f__AnonymousType1<string, System.Collections.Generic.List<<>f__AnonymousType2<string, string>>>>} }

In short: I would like to access the Text fields of the collection.

Here is the QuickWatch window showing the structure and data of this object: QuickWatch Window

Would appreciate any help!

PS: Cannot change the code in the sending method.

Community
  • 1
  • 1
mrkozma
  • 3
  • 2
  • `result.Variants.SelectMany(v => v.Items.SelectMany(i => i.Text))` ? – vasily.sib Jan 22 '20 at 04:09
  • How does `items` look like? It is a list of tuples? Please, share it. You can also have a look at this [thread](https://stackoverflow.com/questions/1203522/how-to-access-property-of-anonymous-type-in-c) for some examples – Pavel Anikhouski Jan 22 '20 at 09:56
  • @PavelAnikhouski The signature of `items` is: `IEnumerable>>>>` – mrkozma Jan 22 '20 at 14:15

1 Answers1

0

If you don't have a static type of a class you can't cast to it. For anonymous types having its type means you either have it locally in the method or get as parameter of a generic method - neither is the case here.

You options are really limited to some sort of reflection to dig into anonymous class. The easiest way would be to let runtime deal with reflection by relying on dynamic like ((dynamic)myVariable).Text.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • I accept this as the answer. It gave me some thoughts and directions to solve the problem. Thank you. – mrkozma Jan 25 '20 at 19:53