Click here to Skip to main content
15,867,568 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello

I am creating a music player.
I have this class:

C#
class Song
    {
        internal int length { get; set; } //the length of the song 
        internal string FullPath { get; private set; } //full path like C:\\Music\song.mp3
        internal string Directory { get; private set; } //e.g C:\\Music
        internal string Name { get; private set; } // e.g song.mp3
        public Song(string path)
        {
            FullPath = path;
            Directory = System.IO.Path.GetDirectoryName(path);
            Name = System.IO.Path.GetFileNameWithoutExtension(path);
        }
    }


I also have a dictionary which holds all the instances of this class for each song which the user inputs.

I am looking for a way to retrieve the
C#
int length
from any instance of the class 'Song' stored in the dictionary just by using the song name...
The way I retrieve the song name is by getting the URL of the Windows Media Player control I'm using..

so I am looking for something like this
C#
int x = Dictionary[wmp.URL.ToString()].length 


(I know that code will not work but I just wanted to give an idea of what I was asking)

I really hope there is someone who can understand what I'm asking and can help :)
Posted

1 solution

First of all, System.Collections.Generic.Dictionary<TKey, TValue> has two generic parameters, not one. The access is done via the keys, so you need a type for a key and a type for a value. The key should be unique. What is it? Say, the full title of the song, then a string. If not, it could be a combination of the title, the year of first release and the names of the authors. In this case, you need a class or a structure of the keys. Also, you need to override the equivalence/identity methods in the key type with its GetHashCode; the hash code override is actually formally required if you override System.Object.Equals and is actually used by key/value associated containers.

Please see:
http://msdn.microsoft.com/en-us/library/system.object.aspx[^],
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx[^].

One minor problem is redundant Directory and Name (file name in your interpretation). This is just a design bug (please see: http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[^]). In this way, it's possible to create instances contradicting to each other. Never do such things. Say, introduce a full-path FileName; but you can also have properties for file name and directory, but returning values on the fly based on full name and the use of System.IO.Path methods.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900