1

I hava a text file containing the following information:

Sandy Princeton 12/24/2013 04.23pm
Crystalline Becker 10/23/2014 06.45pm
Madison Fernandez 01/29/2013 09.45pm
Kroner Mettigot 02/26/2013 10.32am

I've written code that reads the information into into a string[]:

string[] MyArray = allText.Split( new string[]{" ",Environment.NewLine} ,
                     StringSplitOptions.RemoveEmptyEntries
                     ) ; 

How i can sort and store the following information in a multidimensional array. The display in the console should like the one below.

Sandy Princeton       12/24/2013      04.23pm
Crystalline Becker    10/23/2014      06.45pm
Madison Fernandez     01/29/2013      09.45pm
Kroner Mettigot       02/26/2013      10.32am
5
  • Where's the sorting happening at? Your results aren't sorted in any discernible order. Commented Jul 25, 2013 at 18:57
  • Sort by what criteria? First name? Commented Jul 25, 2013 at 19:06
  • What have you tried so far? can you show us an attempt? Each line represents an object: design a class to hold the information contained on each line. Then, read the file line by line, parse each line into its constituent fields. Instantiate an instance of the class you just designed and pour the data gleaned from the line into that instance. Finally add that information into a List<T>, where T is your class name. Then sort your list and turn it into an array. Commented Jul 25, 2013 at 19:08
  • Names, Dates and Time. Only the specified format should be allowed and that would be the criteria. Commented Jul 25, 2013 at 19:21
  • Its like scheduler where i can just see whom to meet and when. Commented Jul 25, 2013 at 19:31

5 Answers 5

2

You need to read one line at a time and split that. Use StreamReader to do so.

Instead of a string array, I'd recommend making a simple container class (firstname, last name, date, time). Then you would just parse your line into an instance of the class and add that to a List.

Sign up to request clarification or add additional context in comments.

Comments

0

If it's always three columns you can just split each line and populate the 2D array cell by cell:

string[,] My2DArray = new string[MyArray.Length,3];

for(int i = 0; i< MyArray.Length; i++)  
{
   string[] items = MyArray[i].Split(' ');
   My2DArray[i,0] = string.Join(" ",items.Take(items.Length-2).ToArray());
   My2DArray[i,1] = items[items.Length-2];
   My2DArray[i,2] = items[items.Length-1];
}

There may be clever ways to do it with Linq but you'll have to use jagged arrays (or nexted lists) as an intermediate step then convert to a rectangular array.

1 Comment

My2DArray will be three times as large as it needs to be. Divide MyArray.Length by 3 in the array allocation.
0
struct Info
{
    string firstName;
    string lastName;
    string date;
    string time;

    String override ToString()
    {
        StringBuilder result = new StringBuilder();
        result.Append(firstName + " ");
        result.Append(lastName + " ");
        result.Append(date + " ");
        result.Append(time + "\n");
        return result.ToString();
    }
}

Read one line a time, split on ' ', like you're already doing. The array you get back from Split will have 4 elements, in the order you show. Just make an Info object, fill the pieces and when you write it out again, you just need to call ToString() on all of your Info objects.

List<Info> lines = new List<Info>();
foreach(Info i in lines)
    Console.WriteLine(i.ToString());

Of course, to have the spacing you want you'll have to use a formatted string, but that's just some changes to the ToString() function where the " " are.

This isn't the whole solution, but it'll get you started.

Comments

0

Declare a class like this

public class Test
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public DateTime dateTime { get; set; }
}

Then write a method like this

List<Test> t = new List<Test>();
using (StreamReader sr = new StreamReader("YourFilePath"))
{
     string line = string.Empty;
     while ((line = sr.ReadLine()) != null)
     {
          string[] lines = line.Split(' ').ToArray();
          //add to your list
          t.Add(new Test() { firstName = lines[0], lastName = lines[1], dateTime = DateTime.ParseExact("MM/dd/yyyy hh:mm:ss tt", lines[2] + lines[3], CultureInfo.InvariantCulture) });
     }
}
//Your Ordered list now
t = t.OrderBy(x => x.dateTime).ToList<Test>();

Comments

0

If you just need the object one time you can make an anonymous class, this would make what you are trying to do a lot clearer in your code

var firstSplit = allText.Split(new[]{Environment.NewLine}, 
                            SplitOptions.RemoveEmptyEntries);
var dataLines = (from i in firstSplit
                 let currLine = i.Split(new[]{" "},SplitOptions.RemoveEmptyEntries)
                 select new 
                 {
                      FirstName = currLine [0],
                      LastName = currLine [1],
                      DateTime = DateTime.ParseExact(currLine[2]+currLine[3],
                                 "MM/dd/yyyy hh.mmtt")
                 }).OrderBy(s=>s.FirstName);

foreach(var line in dataLines)
    Console.WriteLine("{0} {1} {2}", line.FirstName,
                          line.LastName,
                          line.DateTime.ToString("MM/dd/yyyy hh.mmtt"));

or you could just use linq to select a jagged array with the same method, and sort on the whatever field you are looking for, but only if you want to sort based off of alphabetical order.

var fsplt = allText.Split(new{Environment.NewLine},
        StringSplitOptions.RemoveEmptyEntries );
var dataLines = from line in fsplit
                let currLine = line.Split(new[]{" "},SplitOptions.RemoveEmptyEntries)
                orderby currLine[2] //order by the date
                select currLine

foreach(var line in dataLines)
    Console.WriteLine(string.Join(" ",line))

I am not sure what you want to sort by or how you want to sort, so wasn't able to specify what you are looking for. The first method is the best because it establishes that the values should be sorted differently, otherwise you'd have to come up with your own sorting method for each field to sort them correctly without converting them to different objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.