Linking a string with a login [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Im currently making a basic payroll system.
So far I have put all the employee names into a string and an If statement because they all have different hourly rates.
My problem at the moment is linking the same string to the login, so when the employee enters their name and clicks 'login' the program will be able to match the name to the hourly rate when they calculate their weekly hours, tax, pay etc.
Is there a solution/method for this?
string[] employeenames = new string[] { "Jordan", "Ryan", "Dan", };
decimal payRate = 0.0M;
for (int i = 0; i < employeenames.Length; i++)
{
if (employeenames[i] == "Jordan")
{
payRate = 7.20M;
}
else if (employeenames[i] == "Ryan")
{
payRate = 9.47M;
}
else if (employeenames[i] == "Dan")
{
payRate = 13.27M;
}

Although the better option is to use a Database, you can use a switch statement instead.
string loginName = "";
decimal payRate = 0.0 + "M";
switch (loginName){
case "Jordan":
payRate = 7.20 + "M";
break;
case "Ryan":
payRate = 9.47 + "M";
break;
case "Dan":
payRate = 13.27 + "M";
break;
default:
Console.WriteLine("Invalid login name");
break;
}
If you are only using a name to login with, this will be fine. However if you plan on using a password alongside the name, use a database.

So the better way to do this would be to use the following:
Create a class that houses every employee you could want
public class Employee{
public string Name {get;set;}
public double PayRate {get;set;}
}
You can then add employees to a list made out of this class like this:
var employeeList = new List<Employee>();//This list should be populated from the database, below is just proof of concept showing the search syntax
employeeList.Add(new Employee{ Name = "John", PayRate = 33.00});
employeeList.Add(new Employee{ Name = "Steve", PayRate = 2});
employeeList.Add(new Employee{ Name = "Bert", PayRate = 22.99});
The upshot here is you can write a data access method to populate this list from a database.
This will allow you to query against this data in a more meaningful way:
var userLoggedIn = "Steve";
var foundAmmount = employeeList.FirstOrDefault (x => x.Name == userLoggedIn).PayRate;
The above code returns 2.

Related

Trying to pass objects to an array and then search the array to return the object [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
So I'm trying to create a program that will allow me to enter object information to an array and then search that array for pieces of the object and return the object.
At this point I'm not sure if my objects are being put in to the array and if my calls are correct.
Ideally I want to populate the array of objects, then when the menu displays choose a search option. I will search the array of objects for a match and display the object(s) to that match.
I'm not sure where my mistake is as this is not returning my search options. Assistance finding it would be great. Thank you!
static void Main(string[] args)
{
Greeting();
WriteLine();
School [] newStudent = new School[4];
string firstName;
string lastName;
string major;
int id;
double gpa;
for (int i = 0; i < newStudent.Length; i++)
{
GetInfo(out firstName, out lastName, out major);
id = GetId();
gpa = GetGpa();
WriteLine();
newStudent[i] = new School(lastName, firstName, major, id, gpa);
}
DisplayMenu();
int menuOpt = GetChoice();
DoChoice(menuOpt, newStudent);
}
static void Greeting()
{
WriteLine("Student Input");
}
static void GetInfo(out string lastn, out string firstn, out string mjr)
{
Write("Enter student's last name: ");
lastn = ReadLine();
Write("Enter student's first name: ");
firstn = ReadLine();
Write("Enter student's major: ");
mjr = ReadLine();
}
static int GetId()
{
Write("Enter student's ID number: ");
int inum = int.Parse(ReadLine());
while (inum <= 0)
{
Write("ID number must be greater than 0. Please enter student's ID number: ");
inum = int.Parse(ReadLine());
}
return inum;
}
static double GetGpa()
{
Write("Enter student's GPA: ");
double sgpa = double.Parse(ReadLine());
while (sgpa < 0.0 || sgpa > 4.0)
{
Write("That's not a valid GPA. Try Again: ");
sgpa = double.Parse(ReadLine());
}
return sgpa;
}
static void DisplayMenu()
{
WriteLine("1. Search by Last Name");
WriteLine("2. Search by First Name");
WriteLine("3. Search by Major");
WriteLine("4. Quit");
}
static int GetChoice()
{
Write("What is your choice? ");
int select = int.Parse(ReadLine());
while (select < 1 || select > 4)
{
Write("That's not a valid choice. Try Again: ");
select = int.Parse(ReadLine());
}
return select;
}
static void DoChoice(int choice, params School [] nStudent)
{
switch (choice)
{
case 1:
FindLastName(nStudent);
break;
case 2:
break;
//more options will go here at a later date with their matching methods like case 1
}
}
static void FindLastName(params School [] findLName)
{
Write("What is the last name? ");
string findL = ReadLine();
int pos = Array.IndexOf(findLName, findL);
if (pos > -1)
{
PrintStudent(findLName[pos]);
}
else
{
Write("No results found with that last name {0}.", findL);
}
}
static void PrintStudent(School student1)
{
Write(student1.ToString());
}
class School
{
private string lname;
private string fname;
private double gpa;
private string major;
private int id;
public School (string ln, string fn, string maj, int ident, double grade)
{
lname = ln;
fname = fn;
major = maj;
id = ident;
gpa = grade;
}
public string Lname
{
get
{
return lname;
}
set
{
lname = value;
}
}
public string Fname
{
get
{
return fname;
}
set
{
fname = value;
}
}
public string Major
{
get
{
return major;
}
set
{
major = value;
}
}
public override string ToString()
{
string student = lname + ", " + fname + "; " + id + " " + major + " " + gpa.ToString("D2");
return student;
}
UPDATE!: So I have confirmed that my array is populating my objects, however I'm wondering if those values are being passed properly to my methods.
Currently trying to search the array of objects with my FindLastName() method is only returning the else statement as if the values in the array do not exist.
UPDATE 2: After making some suggested changes, I'm about 80% confident my error lies within this method.
static void FindLastName(params School [] findLName)
{
for (int i = 0; i < findLName.Length; i++)
{
WriteLine(findLName[i]);
}
// The above loop proves that the objects exist within the array after being passed to the method.
Write("What is the last name? ");
string findL = ReadLine();
School foundStudent = null;
for (int i = 0; i < findLName.Length; i++)
{
if (findLName[i].Lname == findL)
{
foundStudent = findLName[i];
break;
}
}
if (foundStudent != null)
{
PrintStudent(foundStudent);
}
else
{
Write("No results found with that last name {0}.", findL);
}
// When I run this it returns the else statement even though I am using a last name that exists within the array
It looks to me like you are passing the parameters to GetInfo() in the wrong order, which ends up swapping the person's first name with their last name. So then later, when you're searching for someone by their last name, you will never get a match!
The function signature looks like this (with lastName as the FIRST argument):
static void GetInfo(out string lastn, out string firstn, out string mjr)
But you are calling it like this (with lastName as the SECOND argument):
GetInfo(out firstName, out lastName, out major);
So to resolve this issue, you just need to swap the positions of firstName and lastName in the line above.
Also, I just noticed that you are trying to format the GPA as a date, which will not work. You might consider changing this line:
gpa.ToString("D2")
to this (if you want to show one decimal place):
gpa.ToString("0.0")
You could utilise LINQ to make this search nice and easy with something like this:
string searchValue = PutSearchValueInHere();
School[] selectedStudentArray = schoolArray.Where(school=>school.SearchField == searchValue).ToArray();
School selectedStudent = selectedStudentArray[0]; //Assuming you used a primary key as your search field
Essentially how this works is you pick a field (likely a unique student ID) and a property of your class (eg .StudentID) then pass it into the extention method .Where of your array as a lambda expression. It will then return any items where the lambda evaluates to true.
The expression school=>school.SearchField == searchValue essentially means "Does the search value equal the SearchField of this school object, yes/no?" and it repeats this operation for every item in your array.
Next, the .ToArray() simply tells it to store the results as a new array.
After you've done this, assuming only one student fits the criteria, you are free to select the first item in the array. However, it might be worth checking to see if this is empty or not.
As an after-thought, I really can't help but feel that you should be storing student information in a SQL database and accessing it through an ODBC link, but that's something different entirely.
Based on the concepts it looks like you've learned so far, you probably want to change your logic a little bit in your search algorithm.
What you can do is create a Boolean variable to track whether or not you found any students, and start it off with false
Then loop through your array, one student at a time, and compare the last name to the one we're searching for
If we find the student, output their details and set our Boolean variable to true.
Outside of the loop, we can now just check to see if our variable is false, and if it is we can write the message that no students were found:
The reason using IndexOf wasn't working like you wanted it to is that you have to pass an object of the type stored in the array, and it has to be an exact match to one in the array (the Compare method of the class would return true).
...
static void FindLastName(params School[] findLName)
{
Write("What is the last name? ");
string findL = ReadLine();
// Create a variable to track if we find a match
bool foundStudent = false;
// Search through each array item
for (int i = 0; i < findLName.Length; i++)
{
// See if this item's last name is a match
if (findLName[i].LName == findL)
{
// If it is, set our variable to this student and break out of the for loop
PrintStudent(findLName[i]);
foundStudent = true;
}
}
// If our variable is false (or "not true" in the syntax here), we tell the user
if (!foundStudent)
{
Write("No results found with that last name {0}.", findL);
}
}

How to delete a data from an array in a database (C#)?

I am currently working on a Employee Database using C#. I have 4 different classes which makes up my database; Salaried Employee, Hourly Employee, Commission Employee, and Base-Salaried Employee. I have a base class called "employee" which holds the first name, last name and SSN of each employee type.
At the moment, I am able to individually print each employee when I run the code. I use a test input file which test what type of employee is in the file. It outputs it in an output file with its corresponding type of employee.
Now that, I am able to create an employee record, I also want to be able to remove an employee record from the array.
The method I have for this is called
private void DeleteEmployeeRecord()
{
Console.WriteLine("***** DeleteEmployeeRecord");
}
I am having trouble with getting started with this method. Any tips or idea on how I could delete an employee from the array?
Below is the code for the Employee Database in which does all the operations for the system such as creating a record for employee, finding a record of employee, deleting a record of employee, etc. As I've mentioned, I only have the Create method working and not the rest. I would gladly appreciate any help I can get with understanding how to delete an employee from my temporary array.
**EmployeeDB:**
using System;
using System.IO;
namespace PayrollDB
{
internal class EmployeeDB
{
public const string SALARIED = "SALARIED";
public const string BASEPLUS = "BASEPLUS";
public const string COMMISSION = "COMMISSION";
public const string HOURLY = "HOURLY";
public const char CREATE_C = 'C';
public const char CREATE_c = 'c';
public const char SALARIED_S = 'S';
public const char SALARIED_s = 's';
public const char BASEPLUS_B = 'B';
public const char BASEPLUS_b = 'b';
public const char COMMISSION_M = 'M';
public const char COMMISSION_m = 'm';
public const char HOURLY_H = 'H';
public const char HOURLY_h = 'h';
// storage for all the students during the database operations
private Employee[] employees;
public EmployeeDB()
{
}
internal void ReadDataFromInputFile()
{
// create and intialize the file objects
FileStream fstream = new FileStream("INPUT.txt", FileMode.Open, FileAccess.Read);
StreamReader infile = new StreamReader(fstream); // FileStream
int numberOfRecords = int.Parse(infile.ReadLine());
employees = new Employee[numberOfRecords];
for (int i = 0; i < employees.Length; i++)
{
string employeeType = infile.ReadLine();
// read in data for an employee
string firstName = infile.ReadLine();
string lastName = infile.ReadLine();
string socialSecurityNumber = infile.ReadLine();
// how many more things are there to read?
if(employeeType == SALARIED)
{
decimal weeklySalary = decimal.Parse(infile.ReadLine());
// make a employee using the data you just read
// put the employee into the array
employees[i] = new Salaried(firstName, lastName, socialSecurityNumber, weeklySalary);
}
else if(employeeType == BASEPLUS)
{
decimal grossSales = decimal.Parse(infile.ReadLine());
decimal commissionRate = decimal.Parse(infile.ReadLine());
decimal baseSalary = decimal.Parse(infile.ReadLine());
// make an employee using the data you just read
// put the employee into the array
employees[i] = new BasePlus(firstName, lastName, socialSecurityNumber, grossSales, commissionRate, baseSalary);
}
else if (employeeType == COMMISSION)
{
decimal grossSales = decimal.Parse(infile.ReadLine());
decimal commissionRate = decimal.Parse(infile.ReadLine());
// make a student using the data you just read
// put the student into the array
employees[i] = new Commission(firstName, lastName, socialSecurityNumber, grossSales, commissionRate);
}
else if (employeeType == HOURLY)
{
decimal hourlyWage = decimal.Parse(infile.ReadLine());
decimal hoursWorked = decimal.Parse(infile.ReadLine());
// make a student using the data you just read
// put the student into the array
employees[i] = new Hourly(firstName, lastName, socialSecurityNumber, hourlyWage, hoursWorked);
}
else
{
Console.WriteLine("ERROR: That is not a valid employee type.");
}
}
// close the file or release the resource
infile.Close();
}
internal void WriteDataToOutputFile()
{
// create and open an output file
FileStream fstream = new FileStream("OUTPUT.txt", FileMode.Create, FileAccess.Write);
StreamWriter outfile = new StreamWriter(fstream);
// write the size of the array
outfile.WriteLine(employees.Length);
// write the data from the objects in the array to the output file
foreach (var employee in employees)
{
if (employee is Hourly)
{
var hourly = (Hourly)employee;
outfile.Write(hourly.ToDataFileString());
}
else if (employee is Salaried)
{
var salaried = (Salaried)employee;
outfile.Write(salaried.ToDataFileString());
}
else if (employee is Commission)
{
var commission = (Commission)employee;
outfile.Write(commission.ToDataFileString());
}
else if (employee is BasePlus)
{
var baseplus = (BasePlus)employee;
outfile.Write(baseplus.ToDataFileString());
}
}
// close the output file
outfile.Close();
}
public void PrintAllRecords()
{
Console.WriteLine("** Contents of db ***************");
foreach (var emp in employees)
{
Console.WriteLine(emp);
}
}
// main method that operates the application once we get
// all the data read into it
internal void OperateDatabase()
{
// explain the program to the user
DisplayProgramExplanation();
ConsoleKeyInfo choice;
do
{
// user interface
PresentUserInterface();
//string choice = Console.ReadLine();
//selection = choice[0];
choice = Console.ReadKey();
switch(choice.KeyChar)
{
case CREATE_C:
case CREATE_c:
CreateEmployeeRecord();
break;
case 'F':
case 'f':
FindAndPrintEmployeeRecord();
break;
case 'U':
case 'u':
UpdateEmployeeRecord();
break;
case 'D':
case 'd':
DeleteEmployeeRecord();
break;
case 'P':
case 'p':
PrintAllEmployeeRecords();
break;
default:
break;
}
} while ((choice.KeyChar != 'Q') && (choice.KeyChar != 'q'));
}
private void FindAndPrintEmployeeRecord()
{
throw new NotImplementedException();
}
private void PrintAllEmployeeRecords()
{
Console.WriteLine("***** PrintAllEmployeeRecords");
}
private void DeleteEmployeeRecord()
{
Console.WriteLine("***** DeleteEmployeeRecord");
}
private void UpdateEmployeeRecord()
{
Console.WriteLine("***** UpdateEmployeeRecord");
}
// Find a student object in the array.
// Inputs: email - a string containing the email address of
// the student that is being searched for
// Output: the student object with a matching email, otherwise null ref
private Employee FindEmployeeRecord(string socialSecurityNumber)
{
// look through the collection at each employee
foreach (var emp in employees)
{
// if we find a student with matching social security number
if(emp.SocialSecurityNumber == socialSecurityNumber)
{
// return the object
return emp;
}
}
// if we get through the entire collection with no student
// object find that matches the search email,
// so return a null reference
return null;
}
private void CreateEmployeeRecord()
{
Console.WriteLine(" :: CreateStudentRecord");
//display prompt that asks for employee's social security number
Console.Write("Enter the social security number for the record to add: ");
//user types in the student email
string socialSecurityNumber = Console.ReadLine();
// check to see if record already exists in the database
// if it does, return back to main menu, issue a message
Employee emp = FindEmployeeRecord(socialSecurityNumber);
if(emp != null)
{
Console.WriteLine("Error: " + socialSecurityNumber + " is already in the database.");
return;
}
//display prompt that asks for type of student
Console.Write("Enter the type of employee: ");
ConsoleKeyInfo employeeType = Console.ReadKey();
//display prompt that asks for first name
Console.Write("Enter the first name: ");
string firstName = Console.ReadLine();
//display prompt that asks for last name
Console.Write("Enter the last name: ");
string lastName = Console.ReadLine();
// if type of student was U
if(employeeType.KeyChar == SALARIED_S || employeeType.KeyChar == SALARIED_s)
{
//display prompts for the weekly salary
Console.Write("Enter the weekly salary: ");
decimal weeklySalary = decimal.Parse(Console.ReadLine());
// make an undergrad student
emp = new Salaried(firstName, lastName, socialSecurityNumber, weeklySalary);
}
else if (employeeType.KeyChar == BASEPLUS_B || employeeType.KeyChar == BASEPLUS_b)
{
//if student type is BasePlus Employee prompt for base salary
Console.Write("Enter the Base Salary: ");
decimal baseSalary = decimal.Parse(Console.ReadLine());
// prompt for the Gross Sales
Console.Write("Enter the Gross Sales: ");
decimal grossSales = decimal.Parse(Console.ReadLine());
//prompt for the Commission Rate
Console.Write("Enter the Commission Rate: ");
decimal commissionRate = decimal.Parse(Console.ReadLine());
// make a grad student
emp = new BasePlus(firstName, lastName, socialSecurityNumber, grossSales, commissionRate, baseSalary);
}
else if (employeeType.KeyChar == COMMISSION_M || employeeType.KeyChar == COMMISSION_m)
{
// prompt for the Gross Sales
Console.Write("Enter the Gross Sales: ");
decimal grossSales = decimal.Parse(Console.ReadLine());
//prompt for the Commission Rate
Console.Write("Enter the Commission Rate: ");
decimal commissionRate = decimal.Parse(Console.ReadLine());
// make a grad student
emp = new Commission(firstName, lastName, socialSecurityNumber, grossSales, commissionRate);
}
else if (employeeType.KeyChar == HOURLY_H || employeeType.KeyChar == HOURLY_h)
{
//if student type is BasePlus Employee prompt for base salary
Console.Write("Enter the Hourly Wage: ");
decimal hourlyWage = decimal.Parse(Console.ReadLine());
// prompt for the Gross Sales
Console.Write("Enter the Hours Worked: ");
decimal hoursWorked = decimal.Parse(Console.ReadLine());
// make a grad student
emp = new Hourly(firstName, lastName, socialSecurityNumber, hourlyWage, hoursWorked);
}
else
{
Console.WriteLine(employeeType.KeyChar + " is not a type of employee.");
return;
}
//display the current student data and ask for confirm
// ask user to confirm
// the db saves the record, and returns to main menu - steps:
// and insert the newly created student object into the array
// 1 - make an array that is 1 "bigger" than students
Employee[] biggerEmployeeArray = new Employee[employees.Length + 1];
// 2 - copy all objects from students to the bigger array
// (at the same index val)
for (int i = 0; i < employees.Length; i++)
{
biggerEmployeeArray[i] = employees[i];
}
// put stu in the last slot in the bigger array
biggerEmployeeArray[biggerEmployeeArray.Length - 1] = emp;
// make the students ref point to the bigger array
employees = biggerEmployeeArray;
}
private void PresentUserInterface()
{
Console.WriteLine(#"
Select from the following options:
[C]reate (a new employee)
[F]ind (search for a record)
[U]pdate
[D]elete
[P]rint all records in the database
[Q]uit
");
}
private void DisplayProgramExplanation()
{
Console.WriteLine(#"
********************************************
Welcome to the Employee Database application.
You can execute most typical db commnds,
including
[C]reate, [R]ead [U]pdate, and [D]elete
for the employee records that are present.
");
}
}
}
AS far as I can see, you are not using a real database, but rather an In-Memory-Collection. If you want to keep it like that, you should use another data-structure than an array to store your employees.
You should use something like a Dictionary<string, Employee> where the Key is the social security number, or a HashSet<Employee> and implement GetHashCode() and Equals() in your Employee class.
That way you have collections that will auto-size and from which you can easily remove items using their Remove(...) method.
I suggest you to use a generic List.
private List<Employee> employees = new List<Employee>();
For that you need:
using System.Collections.Generic;
Then you can easliy add employee like this:
employees.Add(emp);
And remove the like this:
employees.Remove(emp);
Your delete method should ask for some kind if identifier so you can search for the right employee and remove him/her afterwards.

How to parse this following string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have to parse this string
"Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing"
as Code, Description like Code=Cust and Description=Customer
split on basis of space is not working for this because there is also a space in description too .
Instead of splitting on space you can split on the equals sign. Then the code will be the value after the last space of the previous item and the description will be everything up to the last space making sure to trim the spaces that might show up before the equals. And you can replace the Dictionary with whatever data type you want to load the values into. Also you have to handle the first and last values as special cases. Note this will only work if the codes do not contain spaces.
string str = "Cust =Customer CustCR =Customer Credit Prod=Product SalesRep=Sales Rep TaxCat=Tax Category TaxId=Tax ID VolBill=Volume Billing";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new Dictionary<string, string>();
for (int i = 1; i < separated.Length - 1; i++)
{
int lastSpace = separated[i].Trim().LastIndexOf(' ');
var description = separated[i].Substring(0, lastSpace).Trim();
codeAndDescription.Add(code, description);
code = separated[i].Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(code, separated[separated.Length - 1]);
foreach (var kvp in codeAndDescription)
Console.WriteLine(kvp);
Outputs
[Cust, Customer]
[CustCR, Customer Credit]
[Prod, Product]
[SalesRep, Sales Rep]
[TaxCat, Tax Category]
[TaxId, Tax ID]
[VolBill, Volume Billing]
A little modification for another case if description is empty, also used custom Item class to store output in a list
class Item {
public string Code { get; set; }
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
string str = "0= 1=Full Time 2=Part Time 3=Seasonal 4=Variable";
var separated = str.Split('=');
string code = separated[0].Trim();
var codeAndDescription = new List<Item>();
foreach (var sep in separated.Skip(1).Take(separated.Length - 2))
{
int lastSpace = sep.Trim().LastIndexOf(' ');
var description = lastSpace != -1 ? sep.Substring(0, lastSpace).Trim(): "" ;
codeAndDescription.Add(new Item { Code=code,Description=description });
code = sep.Substring(lastSpace + 1).Trim();
}
codeAndDescription.Add(new Item { Code = code, Description = separated.Last() });
foreach (var kvp in codeAndDescription)
{
Console.WriteLine("Code={0} Description={1}", kvp.Code, kvp.Description);
}
Console.ReadLine();
}
}

How to read file that contains one row with multiple records- C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have this text file that only has one row. Each file contains one customer name but multiple items and descriptions.
Record starting with 00 (Company Name) has a char length of 10
01 (Item#) - char length of 10
02 (Description) - char length of 50
I know how to read a file, but I don't have any idea of how to loop through only one line, find records 00, 01, 02 and grab the text based on the length, finally start at the position of the last records and start the loop again. Can someone please give me an idea of how to read files like this?
output:
companyName 16622 Description
companyName 15522 Description
input text file example
00Init 0115522 02Description 0116622 02Description
This solution assumes that the data is fixed width, and that item number will preceed description (01 before 02). This solution will emit a record every time a description record is encountered, and deals with multiple products for the same company.
First, define a class to hold your data:
public class Record
{
public string CompanyName { get; set; }
public string ItemNumber { get; set; }
public string Description { get; set; }
}
Then, iterate through your string, returning a record when you've got a description:
public static IEnumerable<Record> ReadFile(string input)
{
// Alter these as appropriate
const int RECORDTYPELENGTH = 2;
const int COMPANYNAMELENGTH = 41;
const int ITEMNUMBERLENGTH = 8;
const int DESCRIPTIONLENGTH = 48;
int index = 0;
string companyName = null;
string itemNumber = null;
while (index < input.Length)
{
string recordType = input.Substring(index, RECORDTYPELENGTH);
index += RECORDTYPELENGTH;
if (recordType == "00")
{
companyName = input.Substring(index, COMPANYNAMELENGTH).Trim();
index += COMPANYNAMELENGTH;
}
else if (recordType == "01")
{
itemNumber = input.Substring(index, ITEMNUMBERLENGTH).Trim();
index += ITEMNUMBERLENGTH;
}
else if (recordType == "02")
{
string description = input.Substring(index, DESCRIPTIONLENGTH).Trim();
index += DESCRIPTIONLENGTH;
yield return new Record
{
CompanyName = companyName,
ItemNumber = itemNumber,
Description = description
};
}
else
{
throw new FormatException("Unexpected record type " + recordType);
}
}
}
Note that your field lengths in the question don't match the sample data, so I adjusted them so that the solution worked with the data you provided. You can adjust the field lengths by adjusting the constants.
Use this like the following:
string input = "00CompanyName 0115522 02Description 0116622 02Description ";
foreach (var record in ReadFile(input))
{
Console.WriteLine("{0}\t{1}\t{2}", record.CompanyName, record.ItemNumber, record.Description);
}
If you read the whole file into a string, you have a couple options.
One, it might be useful to use string.split.
Another option would be to use string.indexof. Once you have the index, you could use string.substring
Assuming fixed-width as specified, lets create two simple classes to hold a client and its related data as a list:
// can hold as many items (data) as there are in the line
public class Client
{
public string name;
public List<ClientData> data;
};
// one single item in the client data
public class ClientData
{
public string code;
public string description;
};
To parse a single line (which is assumed to have a single client and a successive list of item/description), we can do this (note: for simplification I'm just creating a static class with a static method in it):
// this parser will read as many itens as there are in the line
// and return a Client instance with those inside.
public static class Parser
{
public static Client ParseData(string line)
{
Client client = new Client ();
client.data = new List<ClientData> ();
client.name = line.Substring (2, 10);
// remove the client name
line = line.Substring (12);
while (line.Length > 0)
{
// create new item
ClientData data = new ClientData ();
data.code = line.Substring (2, 10);
data.description = line.Substring (14, 50);
client.data.Add (data);
// next item
line = line.Substring (64);
}
return client;
}
}
So, in your main loop, just after reading a new line from the file, you can call the above method to receive a new client. Something like this:
// should be from a file but this is just an example
string[] lines = {
"00XXXXXXXXXX01YYYYYYYYYY02XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXXX",
"00XXXXXXXXXX01YYYYYYYYYY02XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXXX01YYYYYYYYYY02XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXXX",
"00XXXXXXXXXX01YYYYYYYYYY02XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXXX",
"00XXXXXXXXXX01YYYYYYYYYY02XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXXX",
"00XXXXXXXXXX01YYYYYYYYYY02XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXX.XXXXXXXXXX",
};
// loop through each line
// (lines can have multiple items)
foreach (string line in lines)
{
Client client = Parser.ParseData (line);
Console.WriteLine ("Read: " + client.name);
}
Contents of Sample.txt:
00Company1 0115522 02This is a description for company 1. 00Company2 0115523 02This is a description for company 2. 00Company3 0115524 02This is a description for company 3
Note that in the code below, the fields are 2 characters longer than those specified in the original question. This is because I am including the headings in the length of each field, thus a field of a length of 10is effectively 12 by including the 00 from the heading. If this is undesirable, tweak the offsets of the entries in the fieldLengths array.
String directory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
String file = "Sample.txt";
String path = Path.Combine(directory, file);
Int32[] fieldLengths = new Int32[] { 12, 12, 52 };
List<RowData> rows = new List<RowData>();
Byte[] buffer = new Byte[fieldLengths.Sum()];
using (var stream = File.OpenRead(path))
{
while (stream.Read(buffer, 0, buffer.Length) > 0)
{
List<String> fieldValues = new List<String>();
Int32 offset = 0;
for (int i = 0; i < fieldLengths.Length; i++)
{
var value = Encoding.UTF8.GetString(buffer, offset, fieldLengths[i]);
fieldValues.Add(value);
offset += fieldLengths[i];
}
String companyName = fieldValues[0];
String itemNumber = fieldValues[1];
String description = fieldValues[2];
var row = new RowData(companyName, itemNumber, description);
rows.Add(row);
}
}
Class definition for RowData:
public class RowData
{
public String Company { get; set; }
public String Number { get; set; }
public String Description { get; set; }
public RowData(String company, String number, String description)
{
Company = company;
Number = number;
Description = description;
}
}
The results will be in the rows variable.
You would have to split rows based on a delimiter. It would seem that in your case you are using whitespace as a delimiter.
The method you are looking for is String.Split(), it should cover your needs :) Documentation is located at https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx - It also includes examples.
I'd do something like this:
string myLineOfText = "MyCompany 12345 The description of my company";
string[] partsOfMyLine = myLineOfText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
Best of luck! :)

obtaining data from a list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to get data from a list but orderly mer mean get in the order, but I have this code is not working out.
if (item is TextBoxUniversal)
{
foreach (string i in itemlist)
{
ItemValorEntity x = new ItemValorEntity();
x.Item_Id = i[itemIndex].ToString();
strItem = x.Item_Id;
itemIndex += 1;
}
txt.Name = item.Name;
txt = GetTexBox(txt.Name, groupBox1);
itemValor.Item_Id = strItem;
itemValor.cClave = Convert.ToString(cboGTTipoItems.SelectedValue);
itemValor.Valor = txt.Text;
}
In a list I have several items can be 101, 102, 103, etc.. I need to get them in order.
That code only managed to get 1 but is not is 1 is 101
Solucionado
if (item is TextBoxUniversal)
{
string _item = itemlist[itemIndex].ToString();
itemIndex++;
txt.Name = item.Name;
txt = GetTexBox(txt.Name, groupBox1);
itemValor.Item_Id = _item;
itemValor.cClave = Convert.ToString(cboGTTipoItems.SelectedValue);
itemValor.Valor = txt.Text;
}
Updated:
I removed previous answer as I believe this is more what you're looking for. The ability to sort a list that you've received. Your question is still poorly asked, so I'm going to go off some assumptions you've implied. Those are:
Utilize a hard-coded List.
Sort the List.
Display to a user.
The class you'll want to look at for the sort is List(T).Sort it provides a clean, quick, and simple approach to accomplish the goal. Details can be found here.
I'm going to use a more practical scenario, we have a series of students that will require their score / grades be sorted before output to our user.
To begin will build our Student object.
public class Student
{
public string Name { get; set; }
public int Score { get; set; }
public string Grade { get; set; }
}
So far our object is pretty simple, it contains:
Name (Who it is)
Actual score (Numeric Representation)
Grade (Letter Representation)
Now we will implement the IComparable<Student> to our Student object. This will implicitly implement the following method:
public int CompareTo(Student other)
{
throw new NotImplementedException();
}
So we will remove the Exception out of the method and implement:
if(other == null)
return 1;
else
return this.Score.CompareTo(other.Score);
This small amount of code will do the following:
If the object is null it will be greater.
It will compare our current Property to our Parameter Value.
Now all we have to do for our implementation:
// Create Our List
List<Student> student = new List<Student>();
// Add our Students to the List
student.Add(new Student() { Name = "Greg", Score = 100, Grade = "A+" });
student.Add(new Student() { Name = "Kelli", Score = 32, Grade = "F" });
student.Add(new Student() { Name = "Jon", Score = 95, Grade = "A" });
student.Add(new Student() { Name = "Tina", Score = 93, Grade = "A-" });
student.Add(new Student() { Name = "Erik", Score = 82, Grade = "B" });
student.Add(new Student() { Name = "Ashley", Score = 75, Grade = "C" });
// Apply our Sort.
student.Sort();
// Loop through Our List:
foreach (Student placement in student)
listBox1.Items.Add(placement.Name + " " + placement.Score + " " + placement.Grade);
That will put them in a Ascending order. You can tweak and configure to make it Descending should you require it, or even more complex. Hopefully this is a nice starting point.
Also some items have OrderBy or OrderByDescending accessible. So you can actually do code like this to a Dictionary.
student.OrderByDescending(s => s.Value);
You have a slew of possibilities, hopefully this gets you started and able to think about your implementation a bit.

Categories