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;
}
codebehi开发者_如何学运维nd page:
var results = Common.getLogoNav();
foreach(var nav in results) {
string test = nav.Name;
}
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.
Jon Skeet wrote an entry about returning anonymous type. I hope you don't use it.
精彩评论