0

I have list of user class but now i have to return it as a list of object, I try to convert it but it gives me error like. Can not implicitly convert.

Echilon
  • 10,064
  • 33
  • 131
  • 217
girish
  • 701
  • 3
  • 12
  • 22

3 Answers3

7

The simplest solution in .NET 3.5 would be:

List<object> objects = users.Cast<object>().ToList();

Note that this will create a copy of the list. You can't view a List<User> as a List<object> - otherwise you'd be able to do:

objects.Add(new SomeOtherType());

which would clearly break things.

In C# 4, you can use the covariance of IEnumerable<T> to make it slightly simpler:

List<object> objects = new List<object>(users);

or

List<object> objects = users.ToList<object>();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1
public List<Object> ConvertToObjectList<N>(List<N> sourceList)
{
    List<Object> result = new List<Object>();

    foreach(N item in sourceList)
    {
        result.Add(item as Object);
    }

    return result;
}

...

List<Object> myList = ConvertToObjectList<myClass>(myOldList);

I am not sure if I understood your question correctly, but here's my two cents.

Francisco Soto
  • 10,277
  • 2
  • 37
  • 46
0

=/ with linq?

var object_list = from o in user_list
                  select new {
                      User: o.User,
                      Guid: o.Guid
                      // insert properties here
                  }

??????

Germán Rodríguez
  • 4,284
  • 1
  • 19
  • 19