Solved

C# Text file Sort

Posted on 2014-12-28
3
421 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

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…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

772 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

10 Experts available now in Live!

Get 1:1 Help Now