Search code examples
c#objectcastinganonymous

C# Converting an anonymous object with nested collection into an IEnumerable - preferably using the 'as' keyword


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.


Solution

  • 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.