Printing list with additional text - c#

Edit:
So currently I am creating a struct:
struct Coordinate
{
public string Name;
public int HP;
public int EXP;
public Coordinate(string name, int hp, int exp)
{
this.Name = name;
this.HP = hp;
this.EXP = exp;
}
}
}
I have also created this list:
var myList = new List<Coordinate>();
And this is a code i have been working on:
{Console.Write("name:");
string name = Console.ReadLine();
Console.Write("hp:");
int hp = Convert.ToInt32(Console.ReadLine());
Console.Write("exp:");
int exp = Convert.ToInt32(Console.ReadLine());
Coordinate point = new Coordinate(name, hp, exp);
Console.WriteLine("Pokemon's name: "+point.Name);
Console.WriteLine(point.HP); //output: hp inputed
Console.WriteLine(point.EXP); //output: 20
myList.Add(point);
}
else if (menu == '6'){ //need help here, want to print list
}
How to I add the list so that when I input 6, I want to write this:
Pokemon's name = Charmander
Pokemon's HP = 20
Pokemon's EXP = 40

This is probably incorrect:
if (myDictionary.Count <= 0)
{
myDictionary.Add("Pokemon's Name", name);
myDictionary.Add("Pokemon's HP", hp.ToString());
myDictionary.Add("Pokemon's EXP", exp.ToString());
myDictionary.Add("Pokemon's Skill", name);
Console.WriteLine("Pokemon has been added!");
}
First of all, it will only run the code if the dictionary is empty, so trying to add another pokemon will not do anything.
Secondly, it adds the pokemons properties as separate values in the dictionary. So if you remove the Count <= 0 check it will fail since keys are constants and have already been added. Regular dictionaries can only have a single value for a specific key.
You probably want to do the following:
Introduce a Pokemon-class with name, hp, exp and skill properties.
Replace myDictionary with a regular list of pokemons.
Remove the Count <= 0 check
If you only want to allow a single pokemon with a specific name you can keep the dictionary and change it to myDictionary[myPokemonName] = myPokemonObject. This will add a new pokemon, or overwrite any existing pokemon with the same name.

Related

C#: How to find the total sum of arrays inside functions?

I have to create a function that enables me to enter data for every customer in a hardware store. The data that I should enter for every customer is: first name, last name, product bought and its price. This data should be stored in an array. Have this function declare a 1D container, have the user initialise this 1D container with the above data, and have the function return this 1D container back to MAIN. In MAIN, invoke this function three times to create data for 3 customers.
Afterwards, I need to create another function that takes all three 1D containers of customer data from MAIN as parameters and adds up all the prices of the products they bought. Have this function return the total cost back to MAIN. (This is where I'm stuck.)
Lastly, I need to create a procedure that takes the total cost returned to MAIN as parameter and figures out if this total price(set to a simple integer) is a prime number:
if the value is prime, print: "Customers win the Price"
otherwise, print: "Customers won't get the price"
I am stuck on the second function, I tried to do a C-style for loop, but it doesn't work.
I tried to add these three prices as array positions with indices but nothing.
This is the code I have:
using System;
namespace ghghh
{
class Program
{
public static string [] inputData()
{
Console.WriteLine("Please enter your first name: ");
string FirstName = Console.ReadLine();
Console.WriteLine("Please enter your last name: ");
string LastName = Console.ReadLine();
Console.WriteLine("Please enter the product you ahve bought: ");
string product = Console.ReadLine();
Console.WriteLine("Please enter the price: ");
string price = Console.ReadLine();
string[] info = new string[4] { FirstName, LastName, product, price };
return info;
}
public static void sumOfPrice(string[] arr)
{
for(int i = 0; i<arr.Length; i++)
{
string sum = arr[i] + arr[i] + arr[i];
}
}
public static void isTotalCostPrime(int n)
{
if(n %2 == 0)
{
Console.WriteLine("Customers wont get get the prize.");
}
else
{
Console.WriteLine("Customers win the prize");
}
}
public static void Main (string[] args)
{
string[] final = inputData();
sumOfPrice(final);
}
}
}
Here you go with a partial solution to your problem. I made the prices decimal numbers (because most currencies are decimalized). That precludes your prime test at the end.
I also included a quantity. I was tempted to take out the first and last names for each item (since it requires a lot of typing). All in all, though, this should give you enough to get started.
I start with a POCO class to hold the purchased items (POCO stands for "Plain Old CLR Object"; it's a class that consists purely of properties. It's a bit like an old-fashioned C struct.
public class PurchasedItem
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
I separated the user interface out into a separate class (for reasons of separation of concerns). You could easily collapse this into a single class:
public class ItemUserInterface
{
public static PurchasedItem PromptForItem()
{
var purchasedItem = new PurchasedItem();
Console.Write("What is your First Name (or type \"exit\" if complete)? > ");
var firstName = Console.ReadLine();
if (firstName.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
return null;
}
purchasedItem.FirstName = firstName;
Console.Write("What is your Last Name? > ");
purchasedItem.LastName = Console.ReadLine();
Console.Write("What did you purchase? > ");
purchasedItem.ProductName = Console.ReadLine();
purchasedItem.Quantity = PromptForInteger("How many did you buy");
purchasedItem.Price = PromptForDecimal("What was the price");
Console.WriteLine(""); //empty line
return purchasedItem;
}
public static void ShowPurchase (PurchasedItem item)
{
Console.WriteLine($"{item.FirstName} {item.LastName} bought {item.Quantity} of {item.ProductName} at {item.Price} each");
}
public static int PromptForInteger(string prompt)
{
while (true)
{
Console.Write(prompt + " > ");
var entered = Console.ReadLine();
if (int.TryParse(entered, out var result))
{
return result;
}
//otherwise error
Console.WriteLine("Sorry, you must enter a proper integer value");
}
}
public static decimal PromptForDecimal(string prompt)
{
while (true)
{
Console.Write(prompt + " > ");
var entered = Console.ReadLine();
if (decimal.TryParse(entered, out var result))
{
return result;
}
//otherwise error
Console.WriteLine("Sorry, you must enter a proper decimal value");
}
}
}
By the way, while (true) will loop forever unless you do something like return or break out of the loop. Notice that I prompt the user over and over again until he/she enters a correctly formatted number (for the number entries).
Finally, here's my Main routine:
var itemsList = new List<PurchasedItem>();
while (true)
{
var item = ItemUserInterface.PromptForItem();
if (item == null)
{
break;
}
itemsList.Add(item);
}
// at this point, everything is entered
var totalPurchasePrice = 0.00m;
var totalItemsCount = 0;
foreach (var item in itemsList)
{
ItemUserInterface.ShowPurchase(item);
totalPurchasePrice += (item.Quantity * item.Price);
totalItemsCount += item.Quantity;
}
Console.WriteLine($"Purchase Summary: {itemsList.Count} different items ({totalItemsCount} total items) for {totalPurchasePrice:C}");
Console.ReadLine(); //pause
}
If I run this program the output looks like:
What is your First Name (or type "exit" if complete)? > Fly
What is your Last Name? > Dog57
What did you purchase? > Cabbage
How many did you buy > 2
What was the price > 1.99
What is your First Name (or type "exit" if complete)? > Fly
What is your Last Name? > Dog57
What did you purchase? > Hammer
How many did you buy > 6
What was the price > abc
Sorry, you must enter a proper decimal value
What was the price > 10.55
What is your First Name (or type "exit" if complete)? > exit
Fly Dog57 bought 2 of Cabbage at 1.99 each
Fly Dog57 bought 6 of Hammer at 10.55 each
Purchase Summary: 2 different items (8 total items) for $67.28

Binary searching array to display row containing string field

I have a button which should take a 'surname' string input, search a directory array for the 'record' structure correlating to that surname, and output that record to a listview. The directory consists of many rows of 3 string record structures: surname, forename, extcode.
After days of scouring similar SO questions and other sources, I've pieced together the methods which seem to fit my problem best, but my primary search method is not, for some reason, referencing my secondary method. Can you tell me why you think this is, whether you think it will work if I manage to get the reference working, and if not, any alternative suggestions?
FYI my my if statement is a little unruly as my project requires that the surname be case insensitive and accept partial string matches.
private void SearchSurname()
{
Array.Sort(directory, (x, y) => String.Compare(x.surname, y.surname));
ClearForm();
int surnameIndex = Array.BinarySearch(directory, txtSurname.Text);
if (directory[surnameIndex].surname.ToUpper().Substring(0, txtSurname.Text.Length).Contains(txtSurname.Text.ToUpper()))
{
ListViewItem record = new ListViewItem();
// Send each field in current record to single listview item
record.Text = (Convert.ToString(txtSurname.Text));
record.SubItems.Add(Convert.ToString(txtForename.Text));
record.SubItems.Add(Convert.ToString(txtExtCode.Text));
// Display new record listview item in listview
lvDirectory.Items.Add(record);
}
}
public int BinarySearch(string[] directory, string searchTerm)
{
int first = 0;
int last = directory.Length - 1;
int position = -1;
bool found = false;
int compCount = 0;
searchTerm = txtSurname.Text;
while (found != true && first <= last)
{
int middle = (first + last) / 2;
if (string.Compare(directory[middle], searchTerm, true) == 0)
{
found = true;
position = middle;
compCount++;
}
else if (string.Compare(directory[middle], searchTerm, true) > 0)
{
last = middle;
compCount++;
}
else
{
first = middle;
compCount++;
}
}
return position;
}
Edit: Updated code per Olivier Jacot-Descombes' answer:
private void SearchSurname()
{
// Sort directory alphabetically by surname
Array.Sort(directory, (x, y) => String.Compare(x.surname, y.surname));
ClearForm();
// In directory, find line index of search term
int surnameIndex = BinarySearch(directory, txtSurname.Text);
ListViewItem record = new ListViewItem();
// Send each field in current record to single listview item
record.Text = (Convert.ToString(directory[surnameIndex].surname));
record.SubItems.Add(Convert.ToString(directory[surnameIndex].forename));
record.SubItems.Add(Convert.ToString(directory[surnameIndex].extCode));
// Display new record listview item in listview
lvDirectory.Items.Add(record);
}
private int BinarySearch(record[] directory, string searchTerm)
{
int first = 0;
int last = directory.Length - 1;
int surnameIndex = -1;
bool indexFound = false;
// While index not found and there are still points in the array to check
while (indexFound != true && first < last)
{
int middle = (first + last) / 2;
// If surname field in middle record of directory array matches the search term
if (string.Compare(directory[middle].surname, searchTerm, true) == 0)
{
// Index found!
indexFound = true;
surnameIndex = middle;
MessageBox.Show("If 1");
}
// If surname field in middle record of directory array is higher, alphabetically, than the search term
else if(string.Compare(directory[middle].surname, searchTerm, true) > 0)
{
// The next search will be between the first and the current middle records of the array
last = middle;
MessageBox.Show("If 2");
}
// If surname field in middle record of directory array is lower, alphabetically, than the search term
else
{
// The next search will be between the current middle and the highest records of the array
first = middle;
MessageBox.Show("If 3");
}
}
return surnameIndex;
}
Your SearchSurname method calls Array.BinarySearch, which is a static method of the Array Class. If you wanted to call your own method, you would have to write:
int surnameIndex = BinarySearch(directory, txtSurname.Text); // Without "Array."
You are using case-insensitive comparison through the 3rd parameter of String.Compare being true.
You could use
if (string.StartsWith(directory[middle], searchTerm,
StringComparison.CurrentCultureIgnoreCase))
To search only for beginning of names. But there is a problem if several names match. E.g. You are searching for "smit" and you have "Smith" and "Smithy" in the array. Therefore, you would have to test the entries before and after the found match, and return all matching ones as possible results.

Get a variable value from a method to another?

In this situation, I am trying to get the value of "FileSizeType", an integer variable, into the method that's under it "NomCategorie"and convert it to a string(that's what the comment says).
static int ChoisirCategory()
{
int FileSizeType;
Console.Write("What type do you want: ");
FileSizeType = Convert.ToInt32(Console.ReadLine());
return FileSizeType;
}
static string NomCategorie(int c)
{
//get FileSizeType into c
string FileType;
if (c == 1)
{
return FileType = "Small";
}
else if (c == 2)
{
return FileType = "Medium";
}
else if (c == 3)
{
return FileType = "Large";
}
else if (c == 4)
{
return FileType = "Huge";
}
else
{
return FileType="Non-valid choice";
}
I would suggest using enum class
public enum Test
{
Small = 1,
Medium = 2,
Large = 3,
Huge = 4
}
then you can simply convert the number by using
int integer = 1;
if (Enum.IsDefined(typeof(Test), integer)
{
Console.WriteLine((Test)integer).
}
else
{
Console.WriteLine("Bad Integer");
}
output:
Small
Looking at your existing code, you are already returning the value of FileSizeType from the ChoisirCategory, so you can capture it in a variable and then pass that to the NomCategorie method to get the category name, for example:
int categoryId = ChoisirCategory();
string categoryName = NomCategorie(categoryId);
Note that there are many other improvements that can be made (for example, what happens if the user types in "two" instead of "2"?), but I think those suggestions may be out of scope based on the question.
Here's how your code could be simplified if you combine both suggestions above. I've also added an if clause to verify that the value is not higher than those available.
static enum AvailableSizes
{
Small = 1,
Medium = 2,
Large = 3,
Huge = 4
}
static int ChoisirCategory()
{
int FileSizeType;
GetInput:
Console.Write("What type do you want: ");
FileSizeType = Convert.ToInt32(Console.ReadLine());
// Ensure the value is not higher than expected
// (you could also check that it is not below the minimum value)
if (FileSizeType > Enum.GetValues(typeof(AvailableSizes)).Cast<int>().Max());
{
Console.WriteLine("Value too high.");
goto GetInput;
}
return FileSizeType;
}
static string NomCategorie(int c)
{
if (Enum.IsDefined(typeof(AvailableSizes), c)
{
return (AvailableSizes)c;
}
else
{
return "Invalid category";
}
}
Then somewhere in your code you would call these using this statement
string categoryStr = NomCategorie(ChoisirCategory());
Console.WriteLinte(categoryStr); // or do whatever you want with the returned value
With this code, if the input is higher than 4, it will output "Value too high." and ask the question again until the value is no higher than 4.
If the user types 0 or a negative value, then it will output "Invalid category".
This might help you decide where you want to handle input errors: right after user input or during the parsing of the number to a string.

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 count occurences of number stored in file containing multiple delimeters?

This is my input store in file:
50|Carbon|Mercury|P:4;P:00;P:1
90|Oxygen|Mars|P:10;P:4;P:00
90|Serium|Jupiter|P:4;P:16;P:10
85|Hydrogen|Saturn|P:00;P:10;P:4
Now i will take my first row P:4 and then next P:00 and then next like wise and want to count occurence in every other row so expected output will be:
P:4 3(found in 2nd row,3rd row,4th row(last cell))
P:00 2 (found on 2nd row,4th row)
P:1 0 (no occurences are there so)
P:10 1
P:16 0
etc.....
Like wise i would like to print occurence of each and every proportion.
So far i am successfull in splitting row by row and storing in my class file object like this:
public class Planets
{
//My rest fields
public string ProportionConcat { get; set; }
public List<proportion> proportion { get; set; }
}
public class proportion
{
public int Number { get; set; }
}
I have already filled my planet object like below and Finally my List of planet object data is like this:
List<Planets> Planets = new List<Planets>();
Planets[0]:
{
Number:50
name: Carbon
object:Mercury
ProportionConcat:P:4;P:00;P:1
proportion[0]:
{
Number:4
},
proportion[1]:
{
Number:00
},
proportion[2]:
{
Number:1
}
}
Etc...
I know i can loop through and perform search and count but then 2 to 3 loops will be required and code will be little messy so i want some better code to perform this.
Now how do i search each and count every other proportion in my planet List object??
Well, if you have parsed proportions, you can create new struct for output data:
// Class to storage result
public class Values
{
public int Count; // count of proportion entry.
public readonly HashSet<int> Rows = new HashSet<int>(); //list with rows numbers.
/// <summary> Add new proportion</summary>
/// <param name="rowNumber">Number of row, where proportion entries</param>
public void Increment(int rowNumber)
{
++Count; // increase count of proportions entries
Rows.Add(rowNumber); // add number of row, where proportion entry
}
}
And use this code to fill it. I'm not sure it's "messy" and don't see necessity to complicate the code with LINQ. What do you think about it?
var result = new Dictionary<int, Values>(); // create dictionary, where we will storage our results. keys is proportion. values - information about how often this proportion entries and rows, where this proportion entry
for (var i = 0; i < Planets.Count; i++) // we use for instead of foreach for finding row number. i == row number
{
var planet = Planets[i];
foreach (var proportion in planet.proportion)
{
if (!result.ContainsKey(proportion.Number)) // if our result dictionary doesn't contain proportion
result.Add(proportion.Number, new Values()); // we add it to dictionary and initialize our result class for this proportion
result[proportion.Number].Increment(i); // increment count of entries and add row number
}
}
You can use var count = Regex.Matches(lineString, input).Count;. Try this example
var list = new List<string>
{
"50|Carbon|Mercury|P:4;P:00;P:1",
"90|Oxygen|Mars|P:10;P:4;P:00",
"90|Serium|Jupiter|P:4;P:16;P:10",
"85|Hydrogen|Saturn|P:00;P:10;P:4"
};
int totalCount;
var result = CountWords(list, "P:4", out totalCount);
Console.WriteLine("Total Found: {0}", totalCount);
foreach (var foundWords in result)
{
Console.WriteLine(foundWords);
}
public class FoundWords
{
public string LineNumber { get; set; }
public int Found { get; set; }
}
private List<FoundWords> CountWords(List<string> words, string input, out int total)
{
total = 0;
int[] index = {0};
var result = new List<FoundWords>();
foreach (var f in words.Select(word => new FoundWords {Found = Regex.Matches(word, input).Count, LineNumber = "Line Number: " + index[0] + 1}))
{
result.Add(f);
total += f.Found;
index[0]++;
}
return result;
}
I made a DotNetFiddle for you here: https://dotnetfiddle.net/z9QwmD
string raw =
#"50|Carbon|Mercury|P:4;P:00;P:1
90|Oxygen|Mars|P:10;P:4;P:00
90|Serium|Jupiter|P:4;P:16;P:10
85|Hydrogen|Saturn|P:00;P:10;P:4";
string[] splits = raw.Split(
new string[] { "|", ";", "\n" },
StringSplitOptions.None
);
foreach (string p in splits.Where(s => s.ToUpper().StartsWith(("P:"))).Distinct())
{
Console.WriteLine(
string.Format("{0} - {1}",
p,
splits.Count(s => s.ToUpper() == p.ToUpper())
)
);
}
Basically, you can use .Split to split on multiple delimiters at once, it's pretty straightforward. After that, everything is gravy :).
Obviously my code simply outputs the results to the console, but that part is fairly easy to change. Let me know if there's anything you didn't understand.

Categories