Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast an Anonymous Types in Object and retrieve one Field

I use C# asp.net4.

I have a method to populate a Repeater with Anonymous Types (Fields: Title, CategoryId), inside the Repeater I also placed a Label:

        var parentCategories = from c in context.CmsCategories
                               where c.CategoryNodeLevel == 1
                               select new { c.Title, c.CategoryId };
        uxRepeter.DataSource = parentCategories;
        uxRepeter.DataBind();

I need to change Text Properties for each label inside my Repeater on Repeater Event ItemDataBound

   protected void uxRepeter_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        HyperLink link = (HyperLink)e.Item.FindControl("uxLabel");
        uxLabel.Text = // How to do here!!!!!!!! 
    }

So I need set the properties for Label.Text using e.Item (or a better way if any).

My problem I'm not able to CAST the e.Item (Anonymous type Field Title) and set it as Text Propriety for my Label.

I understand Anonymous Type can be casted to only Object Type, but in my case my Anonymous Type has Title and CategoryId Fields.

My question:

How to cast and retrieve the field with I'm interested? Thanks for your time on this?

EDIT: SOME ERROR I RECEIVE:

Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.Int32]' to type 'System.String'.
like image 348
GibboK Avatar asked Aug 01 '11 16:08

GibboK


People also ask

How do I make an anonymous object?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

What are anonymous types in C#?

Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.

Do anonymous types work with Linq?

Use anonymous types with LINQThe Select clause in LINQ creates and returns an anonymous type as a result. The following code snippet illustrates this.

What is the difference between an anonymous type and a regular data type?

From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.


2 Answers

The options Joseph presents are good ones, but there is a horrible way you can do this. It's somewhat fragile, as it relies on you specifying the anonymous type in exactly the same way in two places. Here we go:

public static T CastByExample<T>(object input, T example)
{
    return (T) input;
}

Then:

object item = ...; // However you get the value from the control

// Specify the "example" using the same property names, types and order
// as elsewhere.
var cast = CastByExample(item, new { Title = default(string),
                                     CategoryId = default(int) } );
var result = cast.Title;

EDIT: Further wrinkle - the two anonymous type creation expressions have to be in the same assembly (project). Sorry for forgetting to mention that before now.

like image 125
Jon Skeet Avatar answered Sep 22 '22 22:09

Jon Skeet


You can't cast the anonymous type to anything because you literally have no type to cast it to, as you've basically pointed out already.

So you really have two options.

  1. Don't cast to an anonymous type, but rather a known type that you build just for handling this scenario or
  2. assign a dynamic variable to the item and use dynamic properties instead

Example 1:

var parentCategories = from c in context.CmsCategories
    where c.CategoryNodeLevel == 1
    select new RepeaterViewModel { c.Title, c.CategoryId };

Example 2: (also I think you're last line you meant to assign the link var)

protected void uxRepeter_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    HyperLink link = (HyperLink)e.Item.FindControl("uxLabel");
    dynamic iCanUseTitleHere = e.Item;
    link.Text = iCanUseTitleHere.Title; //no compilation issue here
}
like image 36
Joseph Avatar answered Sep 20 '22 22:09

Joseph