Solved

C# Text file Sort

Posted on 2014-12-28
3
487 Views
Last Modified: 2015-01-13
Hi,
This Following records available in the Text file,
Employee ID:2
Month name:October 2014
Salary:200444
Confirmation Payments:Y

Employee ID:1
Month name:December 2014
Salary:20099
Confirmation Payments:Y

Employee ID:3
Month name:November 2014
Salary:2005
Confirmation Payments:Y

i need to sort , Latest Months Data I need to get first any idea appriciate.
0
Comment
Question by:ukerandi
3 Comments
 
LVL 35

Expert Comment

by:Miguel Oz
ID: 40521122
Q1. Is there any possibility for the data to be presented in CSV format or XML?
Easy to parse into an object.
Q2. For sorting purposes. Is it safe to assume that Month name format is "[Full month name][space][year]?
Required for parsing the date string into date time so that we can compare them.
0
 
LVL 23

Assisted Solution

by:Michael74
Michael74 earned 250 total points
ID: 40521137
Create a class to hold the data eg
Class Employee
{
   int ID { get; set; }
   int Salary { get; set; }
   string Confirmation { get; set; }
   string Month { get; set; }

   public Employee () {}

   public Employee (int id, int salary, string confirmation, string month )
   {
       this.ID = id;
       this.Salary = salary;
       this.Confirmation = confirmation;
       this.Month = month;
   }
}

Open in new window


Then read through the file and create a List<Employee> for the current Date

        Employee emp = new Employee();
        List<Employee> employees = new List<Employee>()
        try
        {
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line = sr.ReadToEnd();
                If (line == "") 
                {
                   If (emp.Month == currentMonth)
                   {
                      employees.add(emp);
                   }
                   emp = new Employee();
                }
                else
                {
                    String[] s = line.Split(":");
                    if (s[0] == "Employee ID")
                    {
                        emp.ID = s[1];
                    }
                    else if (s[0] == "Month name")
                    {
                        emp.Month = s[1];
                    }
                    else if (s[0] == "Salary")
                    {
                        emp.Salary = s[1];
                    }
                    else if (s[0] == "Confirmation Payments")
                    {
                        emp.Confirmation= s[1];
                    }
                }
            }
        }
        catch (Exception e)
        {
            // Handle file exception here
        }

Open in new window


The use something like this to sort the list
List<Employee> SortedList = Employees.OrderBy(o=>o.Salary).ToList();

Open in new window

0
 
LVL 16

Accepted Solution

by:
Rose Babu earned 250 total points
ID: 40525265
Hi ukerandi,

Take a look on the code below which will sort the textfile data with latest month as first. It is working fine with the textfile given.

//Call SortTextData() function 

public void SortTextData()
{            
	try
	{
		string line;
		string[] lineSplit;
		Employee Emp = new Employee();
		List<Employee> Employees = new List<Employee>();

		using (StreamReader sr = new StreamReader("TextFile1.txt"))
		{

			while (!sr.EndOfStream)
			{
				line = sr.ReadLine();
			
				if (line.Trim().Length == 0)
				{
					Employees.Add(Emp);
					Emp = new Employee(); ;
				}
				else
				{
					lineSplit = line.Split(':');

					if (lineSplit[0] == "Employee ID")
					{
						Emp.ID = Convert.ToInt32(lineSplit[1]);
					}
					else if (lineSplit[0] == "Month name")
					{
						Emp.Month = lineSplit[1];
						Emp.MonthNumber = Emp.Month.Split(' ')[1] + "" + ReturnMonthNumber(Emp.Month.Split(' ')[0].ToUpper());
					}
					else if (lineSplit[0] == "Salary")
					{
						Emp.Salary = Convert.ToInt32(lineSplit[1]);
					}
					else if (lineSplit[0] == "Confirmation Payments")
					{
						Emp.Confirmation = lineSplit[1];
					}
				}
			}

			if (Emp.Month != "")
			{
				Employees.Add(Emp);
			}

			List<Employee> SortedEmployeesList = Employees.OrderByDescending(o => o.MonthNumber).ToList();

		}
	}
	catch (Exception e)
	{
		
	}
}

public string ReturnMonthNumber(string MonthName)
{
	switch (MonthName)
	{
		case "JANUARY":
			return "01";

		case "FEBRUARY":
			return "02";

		case "MARCH":
			return "03";

		case "APRIL":
			return "04";

		case "MAY":
			return "05";

		case "JUNE":
			return "06";

		case "JULY":
			return "07";

		case "AUGUST":
			return "08";

		case "SEPTEMBER":
			return "09";

		case "OCTOBER":
			return "10";

		case "NOVEMBER":
			return "11";

		case "DECEMBER":
			return "12";
	}

	return "0";
}

Open in new window


 // Employee.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WinAppCSHARP
{
    class Employee
    {
        public int ID { get; set; }
        public int Salary { get; set; }
        public string Confirmation { get; set; }
        public string Month { get; set; }
        public string MonthNumber { get; set; }
    }
}

Open in new window


TextFile1.txt **************************
Employee ID:2
Month name:October 2014
Salary:200444
Confirmation Payments:Y

Employee ID:1
Month name:December 2014
Salary:20099
Confirmation Payments:Y

Employee ID:3
Month name:November 2014
Salary:2005
Confirmation Payments:Y

Employee ID:7
Month name:January 2014
Salary:200444
Confirmation Payments:Y

Employee ID:5
Month name:March 2014
Salary:103429
Confirmation Payments:Y

Employee ID:4
Month name:June 2014
Salary:20489
Confirmation Payments:Y

Employee ID:6
Month name:February 2014
Salary:65482
Confirmation Payments:Y

Employee ID:10
Month name:October 2011
Salary:200444
Confirmation Payments:Y

Employee ID:8
Month name:December 2013
Salary:20099
Confirmation Payments:Y

Employee ID:9
Month name:November 2012
Salary:2005
Confirmation Payments:Y

Employee ID:13
Month name:January 2010
Salary:200444
Confirmation Payments:Y

Employee ID:12
Month name:March 2013
Salary:103429
Confirmation Payments:Y

Employee ID:14
Month name:June 2011
Salary:20489
Confirmation Payments:Y

Employee ID:11
Month name:February 2014
Salary:65482
Confirmation Payments:Y

Open in new window


check this code once and let me know....

--
Rose
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Host asp.net pages 5 26
ASP.NET 5 Templates 2 68
Get size of each directory on each mapped drive 5 24
use of unassigned local variable 'id' 6 32
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now