Home > OS >  C# Generic foreach over IEnumerable of unknown type
C# Generic foreach over IEnumerable of unknown type

Time:05-07

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:

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?

CodePudding user response:

You can do this:

static string GetCsv<T>(IEnumerable<T> items, string separator)
{
    return String.Join(separator, items.Select(x => x.ToString()).ToArray());
}

Check it here

CodePudding user response:

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);
}
  • Related