从DataGrid.ItemsSource检索匿名类型集合 [英] Retrieving Anonymous Type Collection Back From DataGrid.ItemsSource
问题描述
我正在将collection of anonymous type
写入WPF DataGrid.ItemsSource
.现在我想要它回来.我该怎么做,有可能吗?
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?
如何重建匿名类型?
谢谢!
好的.那你能说这行得通吗?
Ok. So could You say will this work?
if(this.AbcDataGrid.ItemsSource != null && this.XyzDataGrid.ItemsSource != null)
{
var abcdata = (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()
};
}
属性Group
和Name
都出现在匿名类型声明中.
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.
如果您确定要使用匿名类型,则可以使用 cast例如:
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 = "" } });
或者您可以使用动态:
var d = (IEnumerable<dynamic>)casted;
请注意,您可以 强制转换为dynamic[]
,但这并不安全.另一种选择是强制转换为dynamic
,完全保留类型安全性.
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.
这篇关于从DataGrid.ItemsSource检索匿名类型集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!