aianLee
aianLee

Reputation: 97

How to use List<dynamic>

I need to get the list of billers from my database. here is my code:

public static List<dynamic> GetBillers()
{
    DataLayer.DLContext context = new DataLayer.DLContext();

    var Billers = (from b in context.Biller
                   where b.IsActive == true && b.IsDeleted == false
                   select new
                   {
                       ID = b.ID,
                       DisplayName = b.DisplayName
                   }).ToList();

    return Billers;
}

I am getting this error:

Cannot implicitly convert type Collections.Generic.List<AnonymousType#1> to System.Collections.Generic.List<dynamic>

Please help.

Upvotes: 3

Views: 165

Answers (3)

daryal
daryal

Reputation: 14929

you can not assign a List<T> to a List<dynamic> object. You need to add each object one by one;

        var temp = new List<dynamic>();
        foreach (object obj in Billers)
        {
            temp.Add(obj);
        }

Upvotes: 0

Alberto
Alberto

Reputation: 15951

Cast to dynamic:

var Billers = (from b in context.Biller
               where b.IsActive == true && b.IsDeleted == false
               select new
               {
                   ID = b.ID,
                   DisplayName = b.DisplayName
               }).ToList<dynamic>();

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063774

(from b in context.Biller
 where b.IsActive == true && b.IsDeleted == false
 select (dynamic) new {
     ID = b.ID,
     DisplayName = b.DisplayName
 }).ToList();

should do the job. Personally, though, I'm not sure it is a particularly helpful move - I would suggest returning a known class / interface instead. dynamic has various uses, but this isn't a good one.

Upvotes: 6

Related Questions