c# print out list.
need to print out the whole list, so far i have.
-snip-
which does work, worked it out after i posted -.- there a better way to do this?
Since you're not using 'i', you could use a foreach loop. You can also get rid of the variable and just do everything in Console.WriteLine().
foreach (var list in playlist){ Console.WriteLine("{0}\t\t{1}\t\t{2}", list.ID, list.Name, list.Rate);}
David's suggestion of configuring the ToString() method in the Playlist class is also a good one if the formatting is the same all the time. That would change it to look more like
foreach (var list in playlist){ Console.WriteLine(list.ToString());}
gonna have to explain that tosting a bit more?
this is for uni and the course says i have to use XML
To set up ToString(), you just need to override it in the class.
class Playlist{ public int ID; public string Name; public int Rating; public override string ToString() { return string.Format("{0}\t\t{1}\t\t{2}", ID, Name, Rating); }}
David also mentioned having another class that holds the list of playlists with it's own ToString() method that constructs and prints everything for you. Something like this
class AllPlaylists{ public List<Playlist> playlist // A better way might be to make the above private and do everything, like Add/Remove through this class // so you're not directly interacting with the list. public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("ID\t\tName\t\tRating"); foreach (var list in playlist) { sb.AppendLine(list.ToString()); } return sb.ToString(); }}
The above class may be a little overkill if all you're doing is printing out the list. However if you need to do other operations on the list of playlists, it can be useful to have that extra level of abstraction.
David can correct me if I interpreted his response incorrectly.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now