Firstly, change the name of your class from "Documents" to "Document": the plural implies it contains more than one document, which it doesn't. What could you call an array of "Documents"? If you do not use plurals for singular objects you can write code which is immediately obvious:
Document[] documents = myLibrary.GetAll("Hamsters");
foreach (Document document in documents)
{
...
}
Additionally, consider changing the name of your StoreObjects class: Does it store "Object" items? or "Document" items?
Secondly, to return a string instead of a void:
public string GetDataOfAll()
{
StringBuilder sb = new Stringbuilder();
foreach (Documents d in this)
{
sb.Append(d.GetData() + "\n");
Console.WriteLine(d.GetData());
}
return sb.ToString();
}
You don't have to use a StringBuilder, you could just concatenate the strings with
myReturnString += d.GetData();
But StringBuilder is a lot more efficient.
Thirdly, to search, provide two routines:
In StoreObjects:
public Document Find(string searchText)
{
foreach (Document document in this)
{
if (document.Find(searchText))
{
return document;
}
}
return null;
}
In Document:
public bool Find(string searchText)
{
bool found = false;
return found;
}
I leave the document search to you, as I have no idea of your document content!
"Should I call which method from my Form? the method in Document or the one in myLibrary?"
In your form, you only need to call the method in your library, you don't need the
foreach
loop as it is inside the library method:
Document d = myLib.Find(txtTitle.Text);
if (d != null)
{
richTextBox1.AppendText(d.GetData() + "\n");
...
}
This way it is kept cleaner: your form doesn't need to know what your library does to store the documents: you just say "Give me this document" and it does all the work. That way, the Library can change in future, without the form having to change to keep up.
For that reason, I wouldn't derive the Library from the List directly, but would embed the list in the library as a private class variable. It means you have to add the "Add" and "Remove" methods yourself, but it abstracts your data store so it is easier to change in future if you need to. The Add and Remove just call the appropriate methods of the private list.