Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access an object properties without casting to a type

Tags:

c#

linq

i am using LINQ to entity to return a list of objects

            var st = personsList.Select(p => new
            {
                ID = p.Id,
                Key = p.Key,
                Name = p.Name,
                Address = p.Address,
                City = p.City,
                PhoneNumber = p.PhoneNumber
            })
            return st.ToList();

after i get the list in another class how can I access each property?

something like

foreach(object s in St)
{
    string name = s.Name;
}

I have no predefined class to cast the object to it.

Can this be done without having to create a class and cast the object to that class type?

Thanks

like image 943
Y2theZ Avatar asked Apr 17 '12 09:04

Y2theZ


1 Answers

Are you using C# 4? You could try using dynamic:

foreach(dynamic s in St)
{
    string name = s.Name;
}

The risk is, of course, that if you try to access a property that the object doesn't have you'll only find out at runtime.

As an aside, wouldn't it make more sense in this case to actually create a class that has all these properties? You clearly need them in several places and you'd get the benefits of type-safety and compile-time errors.

like image 113
Sergi Papaseit Avatar answered Nov 14 '22 23:11

Sergi Papaseit