Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Generic foreach over IEnumerable of unknown type

I’m trying to write a generic static function that takes an instance of an IEnumerable class, the name of a property of and a string separator. It will loop through the instance and with each member of the instance evaluate the property, collecting the values returned in a single string spaced by the separator.

For example, if my collection class contains instances of Person and the property name is "Surname", and my separator is "’, ‘", I might return: "Smith’, ‘Kleine’, ‘Beecham". I might then surround it in single quotes and use it as a list in SQL.

My problem is that I can’t figure out how to iterate over IEnumerable. My code so far:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public static string EnumerableItem2Str<T>(IEnumerable<T> oItems, string cPropertyName, string cSep)
{
    string cOP = "";
            
    try
    {
        foreach (<T> oItem in oItems)
        {
            cOP += CoreHelper.GetPropertyValue(oItems, cPropertyName).ToString();
            if (oItem != oItems.Last()) cOP += cSep;
        }
        return cOP;
    }
    catch (Exception ex)
    {
        return "";
    }
}

public static object GetPropertyValue(object o, string cPropertyName)
{
    return o.GetType().GetProperty(cPropertyName).GetValue(o, null);
}

I get errors on the line foreach (<T> oItem in oItems) the first of which is "type expected" on <T>.

How do I iterate over oItems to get each instance contained within it?

>Solution :

I think you want to do something like this (it does have a null propogation check so if you’re using an old version of C# then you’ll need to remove that question mark before the ‘.GetValue(i)’):

public static string EnumerableItem2Str<T>(IEnumerable<T> oItems, string cPropertyName, string cSep)
{
    var propertyValues = oItems
        .Select(i => i.GetType().GetProperty(cPropertyName)?.GetValue(i))
        .Where(v => v != null)
        .ToList();

    return string.Join(cSep, propertyValues);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading