绑定匿名类型以创建绑定列表

本文关键字:绑定 创建 列表 类型 | 更新日期: 2023-09-27 18:08:59

我试图创建一个BindingList<>从LINQ查询返回的匿名类型,但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);

在最后一行泛型参数放置什么??

绑定匿名类型以创建绑定列表

您可以编写一个扩展方法:

static class MyExtensions
{
    public static BindingList<T> ToBindingList<T>(this IList<T> source)
    {
        return new BindingList<T>(source);
    }
}

,并像这样使用:

        var query = entities
            .Select(e => new
            {
               // construct anonymous entity here
            })
            .ToList()
            .ToBindingList();

如果您需要在其他地方使用此对象,我建议使用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);

您的数据共享的最低公共基类型。例如对象,如果是这样的话。

var tmp =  new BindingList<object>(data);