11.07.2015 Views

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

278CHAPTER 10 ■ LEARNING ABOUT PERSISTENCEif (splitUpText[0].Contains("-")) {string[] dateSplit = splitUpText[0].Split('-');string newDate =dateSplit[0] + "." + dateSplit[1] + "." + dateSplit[2];if (_dates.Contains(newDate)) {continue;}_dates.Add(newDate);retval.Append(newDate);for (int c1 = 1; c1 < 8; c1++) {retval.Append(" " + splitUpText[c1]);}}else {_dates.Add(splitUpText[0]);retval.Append(lineOfText);}Of all the problems we needed <strong>to</strong> solve, this is the trickiest, because it required multiplepieces of code in multiple places. The code processes the data stream and keeps a list of dates.A date is added <strong>to</strong> the list only if the date does not exist in the list, which is checked using theContains() method. The .NET lists expose this method <strong>to</strong> verify if the object being passed <strong>to</strong> itequals one of the list members. The way that most lists implement the method is <strong>to</strong> iterateeach method and call the Equals() method. The catch is that if you declare a cus<strong>to</strong>m type, theEquals() method defaults <strong>to</strong> verifying if one reference value equals another. You would need<strong>to</strong> implement a cus<strong>to</strong>m Equals() method.■Note When you encounter situations where you need <strong>to</strong> write multiple pieces of code in multiple places,that is a sign that you are about <strong>to</strong> create code that is hard <strong>to</strong> maintain. You should take a close look at thecode, and If possible, rewrite it. Of course, this depends on a lot of fac<strong>to</strong>rs. So sometimes, you will need <strong>to</strong>just write the code, test it, and hope that it works.With the final solution, the console application TextProcessor is complete. You couldprocess lot<strong>to</strong>.txt and get a correctly formatted data stream.Piping Binary DataWhen working with the console, for the most part, you will be transferring text data <strong>from</strong> oneprocess <strong>to</strong> another or <strong>from</strong> one file <strong>to</strong> another file. However, when developing in .NET, workingwith text is not always the best choice. A more efficient approach might be <strong>to</strong> s<strong>to</strong>re thedata in a binary format.The easiest way <strong>to</strong> understand the difference between text data and binary data is <strong>to</strong> opena binary file using a text edi<strong>to</strong>r, as shown in Figure 10-8.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!