[英]Binding anonymous type to Create a BindingList
I am trying to create a BindingList<> from anonymous type returned by LINQ query but BindingList<> do not accept anonymous type, following is my code 我试图从LINQ查询返回的匿名类型创建BindingList <>但BindingList <>不接受匿名类型,以下是我的代码
var data = context.RechargeLogs.Where(t => t.Time >= DateTime.Today).
Select(t => new
{
col1 = t.Id,
col2 = t.Compnay,
col3 = t.SubscriptionNo,
col4 = t.Amount,
col5 = t.Time
});
var tmp = new BindingList<???>(data);
In the last line generic argument what to place ??? 在最后一行泛型参数放置什么???
You can write an extension method: 你可以写一个扩展方法:
static class MyExtensions
{
public static BindingList<T> ToBindingList<T>(this IList<T> source)
{
return new BindingList<T>(source);
}
}
and use it like this: 并像这样使用它:
var query = entities
.Select(e => new
{
// construct anonymous entity here
})
.ToList()
.ToBindingList();
If you need to use this object in other places, I would suggest either using dynamic
, or even better, to simply create the object you need as a struct
. 如果你需要在其他地方使用这个对象,我建议使用
dynamic
,甚至更好的方法来简单地创建你需要的对象作为struct
。
public class RechargeLogData
{
public int Id { get; set; }
public string Company { get; set; }
public string SubscriptionNo { get; set; }
public string Amount { get; set; }
public string Time { get; set; }
}
var data = context.RechargeLogs.Where(t => t.Time >= DateTime.Today).
Select(t => new RechargeLogData()
{
Id = t.Id,
Company = t.Compnay,
SubscriptionNo = t.SubscriptionNo,
Amount = t.Amount,
Time = t.Time
});
var tmp = new BindingList<RechargeLogData>(data);
The lowest common base type your data shares. 数据共享的最低公共基类型。 For example object if thats the case.
例如对象,如果是这样的话。
var tmp = new BindingList<object>(data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.