• 0

[C#] Poke Fun @ the New C# Guy


Question

This is my sorting code for a simple program which would read a llist of names (.txt, First Last) and sort those names alphabeta and write into an output file.

I'm new to C# and this program has been on my mind for about 3 weeks on/off (really off??)

As you can see I'm using an ArrayList and StreamReader/Writer.

The routine shown here is just the sorting, the output I have prepared, and will think about once I get passed this part, Can anyone give me some hints to what i'm doing wrong?

using System;

using System.IO;

using System.Collections;

namespace ConsoleApplication1

{

class Class1

{

 

  static void Main(string[]args)

  {

  ArrayList db = new ArrayList ();

 

  string infile,outfile,compare;

  Console.Write("Where is your input file: ");

  infile = Console.ReadLine();

  if (!File.Exists(infile))

    return;

  StreamReader sr = File.OpenText(infile);

  Console.Write("Where is your output file, if the location specified does not exist, I will create it: ");

  outfile = Console.ReadLine();

  if (File.Exists(outfile))

  {

    Console.Write("Would you like me to overwrite this file? (y/n)");

    compare = Console.ReadLine();

    if (compare.Equals("n"))

    return ;

  }

  StreamWriter sw = File.CreateText(outfile);

 

  while ((compare = sr.ReadLine().Trim) != null)

  {

//begin for loop

if (!compare.CompareTo(db[x]).Equals(0))

    db.Add(compare);

 

//End Loop

  }

 

db.Sort();

    for (int x = 1; x <= db.Count; x++)

    {

    sw.WriteLine(db[x - 1]);

    //Console.WriteLine(db.Count + "and" + db[x]);

    }

   

  }

  } 

}

}

edited: o0o0o0o0o, I just employed Sort(), works neat, i'm tryin that, i'll update my new code shortly!

edited: I should probably mention, im using CompareTo locate any duplicates, So basically I can remove those CompareTos and replace them with a single Sort(), and simply add a CompareTo that checks if it's '0' which means a duplicate that should be removed from the arraylist. Easier said than done for me :(

edited: added full code, sorry anyone that had trouble understanding what I was tryin to do, I hope it's easier to give inputs now, and I appreciate it.

Edited by DarkRyu
Link to comment
Share on other sites

10 answers to this question

Recommended Posts

  • 0

I'm goin to remove those 2 CompareTo expressions, and make one that should work in the following manner but doesn't:

loop

if (compare.CompareTo(db[x]).Equals(0)) //this checks if the string "compare" is a duplicate of any element in my "db" arraylist, which I then wish to delete

db.RemoveAt(x); //this feels redundant, I think my logic is backwards because look at the next line

db.Add(x); //I'm adding somethin I just deleted because it had a duplicate

end loop

Link to comment
Share on other sites

  • 0

Yeah, I would figure there would be a sort function. But on the duplicates, why even remove and readd it if it's already there. You should only do that if you're updating, otherwise it's just a waste of time. There's some Collections that will make it so you can't have duplicates too.

Link to comment
Share on other sites

  • 0

Well, your code is not very readable. But I think I see what you're trying to do. Assuming I'm right, there's a much easier way:

StringCollection db = new StringCollection();
StreamReader sr = File.OpenText(infile);
String strLine = sr.ReadLine();
while (strLine != null)
{
   int nIndex = db.IndexOf(strLine);

   if (nIndex == -1)
   {
      //Executes if db does not contain strLine
   }
   else
   {
      //Executes if db does contain strLine
   }

   strLine = sr.ReadLine();
}
sr.Close();

This implementation may or may not be what you want. I don't quite understand why you're using String.CompareTo (actually, I don't undertand that function at all... how can a string be less than or greater than another string?). It LOOKS like you're trying to see if compare exists inside db. If that's the case, this example is much more efficient.

A few comments on your code:

Yes, the loop starts with x = 0. The way you've done it, your code will never hit the last element of the array. The last iteration through the array is db.Count - 1, which you will never check, since when x == db.Count - 1, the value you are actually checking for (x-1) will be db.Count - 2, which is the second last element.

If your array contains only strings, it's more efficient to use StringCollection (that's in the System.Collections.Specialized namespace). Using ArrayList, every element needs to be boxed/unboxed/ToStringed as you're comparing things. Using StringCollection, that's not necessary.

Also (as I showed above), StringCollection.IndexOf (or ArrayList.IndexOf) is a much easier way to compare something than String.CompareTo. The way you've done it, you have to iterate through the entire array every time a line is read. If you get up to search lots of elements (even a couple hundred), you'll incur a huge performance penalty. If you use IndexOf, that's not necessary. IndexOf returns -1 if the object does not exist in the collection, otherwise it returns the index of the object in the collection.

Link to comment
Share on other sites

  • 0
Yeah, I would figure there would be a sort function. But on the duplicates, why even remove and readd it if it's already there. You should only do that if you're updating, otherwise it's just a waste of time. There's some Collections that will make it so you can't have duplicates too.

Hi kjordan2001,

Yes, there is a function I discovered, it's

Sort();

I'm placing it following the script I posted, which is after I have added everything and avoided duplicates in my ArrayList, that way all that's left is outputting my complete ArrayList to a file.

and it alphabetizes the ArrayList for me! saves from a bunch of "Insert" and "RemoveAt"

Here's the new non-redundant code:

if (!compare.CompareTo(db[x]).Equals(0))

    db.Add(compare);

I think that'll work, the "!" should make the difference.

I'm keepin this post updated, to anyone: feel free to input stuff to me, I feel like im makin some progress, but I won't be stayin up much longer it's nearly a quarter to 2AM.

Link to comment
Share on other sites

  • 0
I don't quite understand why you're using String.CompareTo (actually, I don't undertand that function at all... how can a string be less than or greater than another string?).

CompareTo compares it like it would be in a dictionary.

If strA.CompareTo(strB) returns < 0, then strB would come before strA in the dictionary.

If strA.CompareTo(strB) returns = 0, then strB and strA are the same word.

If strA.CompareTo(strB) returns > 0, then strA comes before strB in the dictionary, or strB may be a null reference.

http://msdn.microsoft.com/library/en-us/cp....asp?frame=true

if (!compare.CompareTo(db[x]).Equals(0))
 ? ?db.Add(compare);

The problem with that is you can't do a .Equals to 0. You use ==, !=, >, <, <=, >=, and such to compare primitives (e.g. char, int, float, etc). .Equals is something Objects (Such as a string) uses to compare itself to another object.

Edited by kjordan2001
Link to comment
Share on other sites

  • 0

Yes, That's exactly right as I was instructed. But perhaps IndexOf has better bearing in my case, i'm taking that into consideration atm!

Link to comment
Share on other sites

  • 0

hey dannysmurf

I'm tryin to stick with the instruction set dictated to me, that's the only reason i'm not usin the specialized you suggested, however thanks to the indexOF i've made good progress.

while ((compare = sr.ReadLine()) != null)

  {

   

    for (int x = 0; x <= db.Count; x++)

    if ( db.IndexOf(compare) == -1)

    db.Add(compare);

   

 

  }

 

db.Sort();

there's an update, works with my test file, except I haven't created output to file yet.

Link to comment
Share on other sites

  • 0

Success!!!

using System;

using System.IO;

using System.Collections;

using System.Collections.Specialized;

namespace ConsoleApplication1

{

class Class1

{

?

? static void Main(string[]args)

? {

?  ArrayList db = new ArrayList ();

?

?  string infile,outfile,compare;

?  Console.Write("Where is your input file: ");

?  infile = Console.ReadLine();

?  if (!File.Exists(infile))

? ? return;

?  StreamReader sr = File.OpenText(infile);

?  Console.Write("Where is your output file, if the location specified does not exist, I will create it: ");

?  outfile = Console.ReadLine();

?  if (File.Exists(outfile))

?  {

? ? Console.Write("Would you like me to overwrite this file? (y/n)");

? ? compare = Console.ReadLine();

? ? if (compare.Equals("n"))

? ?  return ;

?  }

?  StreamWriter sw = File.CreateText(outfile);

?

?  while ((compare = sr.ReadLine()) != null)

?  {

? ?

? ? for (int x = 0; x <= db.Count; x++)

? ? if ( db.IndexOf(compare) == -1)

? ?  db.Add(compare);

? ?

?  }

db.Sort();

?  Console.WriteLine(db.Count);

?  for (int x = 0; x < db.Count; x++) // <=

? ? sw.WriteLine(db[x]);

?  sw.Close();

? }?

}

}

/*

?  StringCollection db = new StringCollection();

?  while ((compare = sr.ReadLine) != null)

?  {

? ? int nIndex = db.IndexOf(compare);

? ? if (nIndex == -1)

? ? {

? ?  //Executes if db does not contain strLine

? ? }

? ? else

? ? {

? ?  //Executes if db does contain strLine

? ? }

? ? compare = sr.ReadLine();

?  }

?  */

Also, I noticed I left the specialized (is it a class or a method, im think the latter) in there, i'll take that out, but it serves for good reference to me!

Edited by Keldyn
Link to comment
Share on other sites

  • 0
Also, I noticed I left the specialized (is it a class or a method, im think the latter) in there

Actually I'd call that neither. A class is the framework for an Object. It's composed of methods and variables. It's made by doing:

class YourClass {

//body of class

}

A method is something you call such as:

int myMethod(int x,int y,string s) {

//body of method

}

What you're referring to is just a segment of code.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.