Passing a property as a parameter in a method

I know that the name may be a little more descriptive / better worded, but that was the best I could come up with.

I currently have a class with many methods that look like this:

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(); foreach (AudioInfo entry in library_entries) { years.Add(entry.Year, entry); } } 

Needless to say, writing dozens of them is very tedious. Therefore, I was wondering if it is 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. } 

This is doable, and if so; as?

Thanks!

+5
source share
1 answer

It seems that you have design errors in your class if you need to do such things. however, the solution is this:

 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 following is used:

 Update(years, x => x.Year); 

You can also use a simpler method, instead of calling any methods that you can simply write:

 years = library_entries.ToDictionary(x => x.Year, x => x); 

If you do not have any events related to your dictionary.

And one more thing - you cannot add different elements with the same keys to the dictionary. In your case, it seems that you have different AudioInfo objects with the same Year , Genre etc

+15
source

Source: https://habr.com/ru/post/898143/


All Articles