基于 lambda 表达式创建匿名类型
我正在尝试为 Winforms Datagrid 创建一个流畅的界面。 这应该允许我使用类型化数据源并轻松使用属性的属性(Order.Custom.FullName)
我在初始化时添加列并尝试设置要在那里使用的属性:
dgv.With<Order>().Column("Client Name").On(x => x.Client.FullName);
然后在设置数据源:
dgv.SetTypedDatasource<T>(IList<Order> orders)
这里的一个大问题是通用控件是不可能的(我猜),因此不能为类指定 T,但必须为每个方法指定...
我想创建一个匿名类型列表,基于lambda 表达式中的给定属性:
类似于:
ProcessList<Client>(clientList, x => x.FullName);
是否可以执行以下操作:
[编辑] 请注意,在实践中,表达式将提前设置,并将在其他地方获取...
public void ProcessList<T>(IList<T> sourceList, Expression<Func<T, object>> expression)
{
var list =
(from T x
in sourceList
select new { expression })
.ToList();
// process list .... grid.DataSource = list;
}
所以,我想创建基于给定表达式的匿名类型。 我知道我可以评估该表达式以检索正确的属性。
我有点卡住了,这样的事情可能吗?
有任何想法吗?
I'm trying to create a Fluent Interface to the Winforms Datagrid. This should allow me to use a typed datasource and easy use of properties of properties (Order.Custom.FullName)
I'm adding the columns on initialization and trying to set the property to use there:
dgv.With<Order>().Column("Client Name").On(x => x.Client.FullName);
The original question then poses itself when setting the Datasource:
dgv.SetTypedDatasource<T>(IList<Order> orders)
A big problem here is that Generic Controls are not possible (I guess), so that T cannot be specified for the class, but has to be specified per method...
I want to create a list of anonymous types, based on a given property in a lambda expression:
something like:
ProcessList<Client>(clientList, x => x.FullName);
Is it possible to do something like this:
[Edit] Note that in practice, the expressions will be set earlier, and will be fetched elsewhere...
public void ProcessList<T>(IList<T> sourceList, Expression<Func<T, object>> expression)
{
var list =
(from T x
in sourceList
select new { expression })
.ToList();
// process list .... grid.DataSource = list;
}
So, I would like to create anonymous types based on the given expression. I know I can evaluate that expression to retrieve the correct properties.
I'm kinda stuck, is something like this possible?
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,通过简单地调用
Select
,您就可以非常接近:(假设您也不需要
ProcessList
中的原始列表如果这样做,请将选择移到那里。)Well, with a simple call to
Select
you can come very close:(That assumes you don't need the original list in
ProcessList
as well. If you do, move the select into there.)这不就是 grid.DataSource = sourceList.AsQueryable().Select(expression).ToList();
请注意,最好引入第二个泛型,以便输入列表:
请注意,我从
Expression<...>
切换为Func<...>
,因为它似乎没有任何作用。isn't that just
grid.DataSource = sourceList.AsQueryable().Select(expression).ToList();
Note that it would be better to introduce a second generic, such that the list is typed:
Note I switched from
Expression<...>
to justFunc<...>
, as it seemed to serve no purpose.