Binding anonymous type to Create a BindingList

前端 未结 3 1957
执念已碎
执念已碎 2020-12-30 14:02

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

v         


        
相关标签:
3条回答
  • 2020-12-30 14:08

    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();
    
    0 讨论(0)
  • 2020-12-30 14:24

    The lowest common base type your data shares. For example object if thats the case.

    var tmp =  new BindingList<object>(data);
    
    0 讨论(0)
  • 2020-12-30 14:26

    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.

    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);
    
    0 讨论(0)
提交回复
热议问题