开发者

Retrieving Anonymous Type Collection Back From DataGrid.ItemsSource

开发者 https://www.devze.com 2023-03-11 13:32 出处:网络
I\'m writing a collection of anonymous type into WPF DataGrid.ItemsSource. And now I want it back. How do I do this, Is it possible?

I'm writing a collection of anonymous type into WPF DataGrid.ItemsSource. And now I want it back. How do I do this, Is it possible?

How can I reconstruct the anonymous type?

Thanks!

EDIT

Ok. So could You say will this work?

if(this.AbcDataGrid.ItemsSource != null && this.XyzDataGrid.ItemsSource != null)
{
    var 开发者_如何学Goabcdata = (IEnumerable<dynamic>)this.AbcDataGrid.ItemsSource;
    var xyzdata = (IEnumerable<dynamic>)this.XyzDataGrid.ItemsSource;

    var d1 = abcdata.ToList().OrderByDescending(x => x.Id);
    var d2 = xyzdata.ToList().OrderByDescending(x => x.Id);

    var result = from i1 in d1
                 from i2 in d2
                 select new
                 {
                     Name  = i1.Name,
                     Group = i1.Group.ToString() + i2.Group.ToString()
                 };
} 

Properties Group and Name both present in anonymous type declaration.


There are several options, but the best one is: don't do it. Anonymous types are meant to be used only in one function, not to store them somewhere and then retrieve them. Just create a normal class.

If you are sure you want to use anonymous type, you could use cast by example:

var anons = new[] { new { prop1 = 1, prop2 = "bar" }, new { prop1 = 42, prop2 = "foo" } };
IEnumerable casted = anons;
var castedBack = CastByExample(anons, new[] { new { prop1 = 0, prop2 = "" } });

Or you could use dynamic:

var d = (IEnumerable<dynamic>)casted;

Note that you could cast to dynamic[], but doing so is not safe. Another option would be to cast to just dynamic, leaving type-safety completely.


You will have to treat it as a dynamic type. See http://msdn.microsoft.com/en-us/library/dd264736.aspx

However, I would suggest you use a named class so that the producer and consumers can agree on the data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号