Michael Evans
Michael Evans

Reputation: 39

Search a list by keyword and get object content

I'm new to C#, in my case switch 2 I would like the user to input a keyword, for instance, if a song name is HelloWorld the user should find the song by typing "he", and for every song that exists in the list that matches the keyword. The song, artist, and song duration gets printed out. I have tried several methods but i cant figure out.

I have a List of this class:

class Song{
private string _artist;
private string _song;
private int _duration;
}

//This is my switch statement

                        //List
                    List<Song> music = new List<Song>();

                       //Song object
                    Song newsong = new Song();


                    //Switch Statement

                   case 1:
                    Console.WriteLine("\nAdd a song.");
                    Console.WriteLine("Artist name:");
                    newsong.Artist = Console.ReadLine();
                    Console.WriteLine("Name of song:");
                    newsong.mottagenSongNamn = Console.ReadLine();
                    Console.WriteLine("Song duration:");
                    newsong.Duration = int.Parse(Console.ReadLine());


                    music.Add(new Song(newsong.Artist, newsong.mottagenSongNamn, newsong.Duration));
                    Console.WriteLine("Song added.");
                    Console.ReadKey();
                    break;


                case 2:

Previously i tried the code underneath but it doesn't work

  string keyword =  Console.ReadLine();
                   foreach(var item in music)
                    {
                        if(music.Contains(keyword)) {
                            Console. WriteLine(item);
                        }  
                             }

Upvotes: 0

Views: 87

Answers (1)

pm100
pm100

Reputation: 50210

first of all all that data is private, make it public if you want to search from 'outside' the class.

class Song{
   public string _artist;
   public string _song;
  public int _duration;
}

if you have a string to match called keyword

 var found = music.Where(x=>x._song.Contains(keyword));

assuming 'music' is a list of Song objects. This will find matching songs


If you want to display this list

 foreach(var song in found){
    Console.WriteLin(song._song);
 }

Upvotes: 2

Related Questions