Question

I have a function which skim through a list of object (Genre, Nationality, etc). It has to return the addition of a specific property (Different for each object). I can't modify the code of these listed objects (in a DDL).

Here some examples of what I have to do for now :

    private String formatListString(List<Genre> list)
    {
        for (...)
        {
            str += list[i].Value;
            ...
        }
        return str;
    }

    private String formatListString(List<Nationality> list)
    {
        for (...)
        {
            str += list[i].Code;
            ...
        }
        return str;
    }

How can I make it in one single function ? Maybe add a parameter in the function to specify the property to use ?

Thanks.

Était-ce utile?

La solution 2

You can pass in a lambda to select the property you need:

private String formatListString<T>(List<T> list, Func<T, string> selector)
    {
        for (...)
        {
            str += selector(list[i]);
            ...
        }
        return str;
    }

Call as follows:

var genres = formatListString(genreList, x => x.Value);
var nationalities = formatListString(nationalityList, x => x.Code);

The generic type parameter can be automatically inferred from the call, so you don't have to specify it explicitly (i.e. write formatListString<Genre>(genreList, x => x.Value);)

Autres conseils

return String.Join("...", list.Select(o => o.Code));

If that won't work for you, you could use generics and a lambda:

private string FormatList<T>(IEnumerable<T> list, Func<T, String> prop)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top