Friday, November 21, 2008

Trips&Ticks: Do you know how you can cast Object to AnonymousType?

I experimented with LINQ in my private project and question that was showed in title took me. I had next situation:

I set list in one method:

private void SetList()
{
SomeList.ItemsSource = ( from someTable in data.SomeTable
select new
{
someTable.Id,
someTable.Name,
Priority = someTable.Priority,
} );
In other method I want retrieve Id of selected item. How can I do it? I have found interesting solution in blog of Tomas Petricek.
private Int32 GetID()
{
Object selectedItem = DefectList.SelectedItem;

if( null != selectedItem )
{
var item = Utility.Cast( selectedItem, new
{
Id = 0,
Name = String.Empty,
Priority = String.Empty,
} );

Int32 id = item.Id;
}
}
public static T Cast( object obj, T type )
{
return (T)obj;
}

PS: As for me the best way is:
  • implement class with three like property.
  • create collection with items of this class.
  • set in ItemsSource new created collection.
  • now we can easy case Object to this class.

No comments: