Access properties of <T> object

Viewed 42

This is the extension method I have written :

    public static class ExtensionMethods
    {
        public static string Syngen<T>(this IEnumerable<T> list, string separator)
        {
            StringBuilder sb = new StringBuilder();
            foreach (T obj in list)
            {
                if (sb.Length > 0)
                {
                    sb.Append(separator);
                }
                sb.Append(obj);
            }
            return sb.ToString();
        }
    }

This is where I am accessing from a razor component

-- Questionnaire is an class containing some properties
context.Items.Syngen<Questionnaire>(":")

How do I access the property of this class? (Obj) I need to access one property of this object.

I have even used Questionnaire instead of T but still unable to access obj. During runtime I am able to see all the properties of the obj, but during design/compile time, I am unable to list the properties of obj.

2 Answers

Assuming your objects have the same interface or base class implementing the property.

public static string Syngen<T>(this IEnumerable<T> list, string separator)
    where T : ISomeInterfaceOrBaseClass =>
    list.Select(a => a.SomeProperty).Aggregate((a,b) => $"{a}{seperator}{b}" );


public interface ISomeInterfaceOrBaseClass  
{
    string SomeProperty { get; }
}
public static string Syngen<T>(this IEnumerable<T> list, string separator) where T : class
        {
            StringBuilder sb = new StringBuilder();
            foreach (T obj in list)
            {
                if (sb.Length > 0)
                {
                    sb.Append(separator);
                }
                sb.Append(obj);
            }
            return sb.ToString();
        }

This worked

Related