Passing property as parameter in method
I know the title could probably be a bit more descriptive/better phrased, but it was the best I could come up with.
Currently I have a class with a lot of methods looking like the ones below:
private static void UpdateArtists()
{
artists.Clear();
foreach (AudioInfo entry in library_entries)
{
artists.Add(entry.Artist, entry);
}
}
private static void UpdateAlbums()
{
albums.Clear();
foreach (AudioInfo entry in library_entries)
{
albums.Add(entry.Album, entry);
}
}
private static void UpdateGenres()
{
genres.Clear();
foreach (AudioInfo entry in library_entries)
{
genres.Add(entry.Genre, entry);
}
}
private static void UpdateYears()
{
years.Clear();开发者_StackOverflow中文版
foreach (AudioInfo entry in library_entries)
{
years.Add(entry.Year, entry);
}
}
Needless to say, writing dozens of these is very tiresome. So I was wondering if it's possible to simplify it and make a method something like this:
private static void Update(Dictionary<string, AudioInfo> dictionary, AudioInfo.Property property)
{
dictionary.Clear();
foreach (AudioInfo entry in library_entries)
{
dictionary.Add(entry.property, entry);
}
//Where "property" is a property in the AudioInfo-class.
}
Is that doable, and if it is; how?
Thanks!
It seems like you have some design errors in your class if you need to do such things. nevertheless, the solution is:
private static void Update(Dictionary<string, AudioInfo> dictionary, Func<AudioInfo, string> func)
{
dictionary.Clear();
foreach (AudioInfo entry in library_entries)
{
dictionary.Add(func(entry), entry);
}
}
And the usage is:
Update(years, x => x.Year);
Also you can use easier way, instead of call any methods you can just write:
years = library_entries.ToDictionary(x => x.Year, x => x);
If you have not any events, linked with your dictionary.
And one more thing to go - you can't add different elements with the same keys to dictionary. In your case it seems like you have different AudioInfo
objects with the same Year
, Genre
e.t.c.
精彩评论