Access to object properties without casting into type

I use LINQ for an 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?

sort of

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

I do not have a predefined class to cast an object to it.

Is it possible to do this without creating a class and casting the object to the type of this class?

thank

+3
source share
4 answers

You can use the following command

foreach(object s in St)
{
   Type type = s.GetType();
   PropertyInfo property = type.GetProperty("Name");
   if(property !=null)
   {
       string name= (string )property.GetValue(s, null);
   }
}

you need to add the System.Reflection namespace to the class

+3
source

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

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

Of course, the risk is that if you try to access a property that the object does not have, you will only recognize it at run time.

, , ? , .

+7

C # 3.0 has a type varthat allows for implicit casting.

0
source

The compiler creates an anonymous type for you that can be used as part of the method. If you need to pass the LINQ query results around, then itโ€™s best to create a domain object to represent information such as PersonSummary and assign the query results to it. C # is strongly typed using this.

0
source

All Articles