Ryan Ayala
Ryan Ayala

Reputation: 77

How to get Array Items inside of List<object> c#

How to get Array Items inside of List c#

IEnumerable<object> enumerable = c1._getbrandrequest(object[]);

List<object> brand = enumerable.Cast<object>().ToList();

List<Brand> brands = new List<Brand>();

for (int i = 0; i <= enumerable.Count(); i++)
{

    var brnd = enumerable.ElementAt(i);

    // brnd (intellisense only produce)
    // brnd. { Equals, GetHashCode, GetType, ToString }

}

Image of ArrayItems from Web Services

thanks in Advance!

Upvotes: 3

Views: 1449

Answers (3)

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

If enumerable contains Brand objects, then what you need is cast the element returned by enumerable.ElementAt(i):

var brnd = enumerable.ElementAt(i) as Brand;

Upvotes: 1

Ryan Ayala
Ryan Ayala

Reputation: 77

        var enumerable = c1._getbrandrequest( Object[] );

        List<Brand> brands = new List<Brand>();

        foreach (var brnd in enumerable)
        {
            Brand model = new Brand();

            model.sid = brnd.sid;

            brands.Add(model);

        }

Upvotes: 0

Evert
Evert

Reputation: 354

I think your code can be a bit cleaner in this way:

IEnumerable<object> enumerable = c1._getbrandrequest(object[]);
List<Brand> brands = enumerable.OfType<Brand>().ToList();

foreach (Brand brnd in brands)
{
  // Do things with brnd.
}

The OfType only returns objects that have a runtime type Brand, and the result is an IEnumerable, the ToList() makes them into a fresh list.

Upvotes: 1

Related Questions