phxis
phxis

Reputation: 15

.net 3.5 anonymous foreach

I'm trying to loop through the results of a function that is returning an anonymous object of results.

public static object getLogoNav()
{
  XDocument loaded = XDocument.Load(HttpContext.Current.Request.MapPath("~/App_Data/LOGO_NAV_LINKS.xml"));

  var query = from x in loaded.Elements().Elements()
              select new
              {
                 Name = x.FirstAttribute.Value,
                 Value = x.Value
              };

  return query;
}

codebehind page:

  var results = Common.getLogoNav();
  foreach(var nav in results) {
     string test = nav.Name;
  }

Upvotes: 1

Views: 1001

Answers (2)

Tamas Czinege
Tamas Czinege

Reputation: 121304

You can't have an anonymous class as a return type in C# 3 (and 4 for that matter) and you can't cast an object to an anonymous type. Your three options are:

  • Doing the loop within the scope of the anonymous class (most of the time, this is the method)
  • Casting to object and using reflection (slow and not very easy to do unless you do some expression tree magic)
  • Converting to a named class and returning and instance of that.
  • (In C# 4) you can create some dynamic type magic to achieve a similar effect but that would be really the same as option 2 with some syntactic sugar.

Upvotes: 5

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

Jon Skeet wrote an entry about returning anonymous type. I hope you don't use it.

Upvotes: 2

Related Questions