C# Console - Inputting and removing from an array
for part of a small assignment I have, i've been asked to create an array to store names and addresses taken from input that the user gives and to be able to later delete a name and address from the array.
Any help or links to helping me understand how to achieve this would be highly appreaciated, thanks.
EDIT - The array is to be set up like an address book, and when printed to the screen it displays like so: "Bloggs, Joe" It must be surname then forename. I know how to acquire and store the information the user wi开发者_如何学Goll give, being their names and addresses, but I am stuck on how to add this into an array. The array doesn't have to be infinite, as I am supposed to allocate the array whatever size I wish.
At the start of the program it will be part of, the user will be given a menu, and they can choose to add a record, delete a record or print the book to the screen. So i am meant to be using methods where suitable.
Well, to start with, an array is the wrong data structure to use here.
Arrays are always a fixed size - whereas you want to be able to add elements and later remove them. Assuming you're using C# 2 or higher, you should probably use a List<T>
.
Now, the next thing is to work out what T
should be. It sounds like you want to store details of people - so you should create a Person
class (or perhaps Contact
) to encapsulate the name and address... that way you can have a List<Person>
.
The next task is probably to work out how to ask the user for input and convert that input into an instance of Person
.
Basically, break the task up into small bits - and then feel free to ask questions about any specific bits which you find hard.
I seem to remember this exact same assignment from my CS classes.
The prof wanted us to use linked lists. As John Skeet points out above, .NET has List<T>
, which is basically a linked list (with the added feature of being able to be reference each item by index like an array)
You can use a Serializer for the saving part.
Check out the BinaryFormatter class and XmlSerializer. XmlSerializer is preferred because the file is human-readable and efficiency is usually less important considering the type and purpose of your app.
Using XmlSerializer is as simple as:
var filename = "c:\....\addressbook.xml"; if (File.Exists(filename)) File.Delete(filename); using (var sw = new StreamWriter(filename)) { var xs = new XmlSerializer(typeof(List<Person>)); xs.Serialize(sw, myAddressBook); }
精彩评论