Asim Zaidi
Asim Zaidi

Reputation: 28284

get the object properties

I have a code that returns me an object of widgets

XDocument loaded = XDocument.Parse( xml );

var widgets = from x in loaded.Descendants( "widget" )
              select new
              {
                  URL = x.Descendants( "url" ).First().Value,
                  Category = x.Descendants( "PortalCategoryId" ).First().Value
              };

I am trying to create a method that will return the object widgets and then I need another method where I can cal it from and access the values. I am new to C# and using vs2010

thanks

Upvotes: 0

Views: 90

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

change var widgets to dynamic widgets

example

using System;
using System.Linq;

class Sample {
    static object junk(){
        var widgets = new { URL = new Uri("http://test.com/"), Category = "address" };
        return widgets;
    }
    static void Main(){
        dynamic widgets = junk();//var widgets = .. //NG
        Console.WriteLine(widgets.URL);
    }
}

Upvotes: 1

Erik Philips
Erik Philips

Reputation: 54618

Instead of

XDocument loaded = XDocument.Parse( xml ); 

var widgets = from x in loaded.Descendants("widget") 
              select new // Dynamic/Anonymous class
              { 
                URL = x.Descendants( "url" ).First().Value, 
                Category = x.Descendants( "PortalCategoryId" ).First().Value 
              }; 

It would be better to create a concreate class

//Widget.cs
Public class Widget
{
  public string URL { get; set; }
  public string Category { get; set; }
}

//Code somewhere else..
XDocument loaded = XDocument.Parse(xml); 

IEnumerable<Widget> widgets = 
              from x in loaded.Descendants("widget") 
              select new Widget()
              { 
                URL = x.Descendants( "url" ).First().Value, 
                Category = x.Descendants( "PortalCategoryId" ).First().Value 
              }; 

Upvotes: 2

SLaks
SLaks

Reputation: 887305

Anonymous types cannot easily be shared across methods.

You should make a class to store that data.

Upvotes: 4

Related Questions