Save text data to array - c#

I'm very new to working with C#. I am trying to save data (text such as a persons name) which is entered into the console and then 'read' to an array.
The name of the array i want to save data to is: name2convert
The variable collecting the data (name to be converted) is: nameEntered
Any help is very much appreciated. I've been working on this for a few hours and have done several searches, but i have not found any answers which I could understand with my limited understanding of C# at this time. I've only been trying to learn this for a few weeks - i'm very very green. Any help is appreciated.
Note: String names was my test array so that i could see that i knew how to read data back from an array.
I want to save the data to the names2Convert array.
This is my code:
using System;
namespace a061___String_Manipulations___PigLatin
{
///loop - ask for number of names equal to number asked
/// read line, save to array, iterate one up until num equals value asked for
class Program
{
//Arrays
String[] names = { "test01", "test02", "test03", "test04", "test05" }; //Test loop
String[] name2convert = new String[1];
//Variables & Ints?
string title = ">>>-- Welcome to the Highly Enlightening World of Igp-ay Atinl-ay --<<< \n";
string totalIs = "You said you want to convert a total of";
string listCommands = "Is that correct? If so type (Y)es, (R)enter or (Q)uit";// general commands used
string addSuffix ="-ah!"; // Add to end of each name
string nameEntered = "";//name to be converted
int namesTotal = 0;//
//Main Method
public void Play()
{
Console.WriteLine(title); //announce program
askTotal(); //ask number of names
while (true)
{
Console.WriteLine(listCommands);//lists options
String command = Console.ReadLine().ToLower();//reads user command
if (command == "y") // if askTotal true save to array? how?
{
askName();//collects name entered
confirmName();//allows user to confirm spelling, etc.
//y save the array nameEntered name2convert
//name2convert.Add(nameEntered);
name2convert[0] = nameEntered;
//confirm name
for (int i = 0; i < name2convert.Length; i++)
{
Console.WriteLine("Name Aquired: " + name2convert[i]);
}
}
else if (command == "r")
{
askName();//asks name
}
else if (command == "q")
{
Console.WriteLine("Cheers!"); break; //end
}
else
{
Console.WriteLine("Sorry. Invalid Request");//try again
}
PrintList();//test array
}
}
//Helper Methods
public void PrintList()//iterates through, prints names stored in array
{
Console.WriteLine("Print List");
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine((i + 1) + ". " + names[i] + addSuffix);
}
}
//iterates through, prints names stored in array
public void askName()
{
Console.WriteLine("Enter Name: ");//Confirming
String nameEntered = Console.ReadLine().ToLower();// Capture name
Console.WriteLine("Name Captured: " + nameEntered);//confirming name caught
}
//iterates through, prints names stored in array
public void confirmName()
{
Console.WriteLine(listCommands);//Confirming
String command = Console.ReadLine().ToLower();
}
//how many names to convert
public void askTotal()
{
Console.WriteLine("How many names would you like to convert?");//Ask for content
namesTotal = int.Parse(Console.ReadLine());
Console.WriteLine(totalIs + " " + namesTotal);//Confirming
}
//Call Application
static void Main(string[] args)
{
Program StringManipulations = new Program();
StringManipulations.Play(); //Call forth the Pig Latin...
Console.Read();//
}
}
}

Change this:
//y save the array nameEntered name2convert
name2convert.Add(nameEntered);
To this:
name2convert[0] = nameEntered;
EDIT:
In askName() function change:
String nameEntered = Console.ReadLine().ToLower();// Capture name
To:
nameEntered = Console.ReadLine().ToLower();// Capture name
You already have nameEntered of type string declared as property of your class.
And why are you using string and then String? it's the same, as string is alias of String (which is in fact System.String in C#) - but be consistent!
As you already allocated the memory for this array (it's fixed size - in your case it's one).
So to access the first (and only) cell in your array, you should use name2convert[0] - 0 is the first index at any array and usually at any other struct/container in C# (and many other programming languages).
Another approach (as you were trying in your example) is to user List<String> instead.
For more information on arrays and Lists refer to here:
Array tutorial
List tutorial and examples

If you want save EVERY WORD that the user inputs use an List of Strings e.g
List<String> name2convert;
then
name2convert.Add(nameEntered);
to go through the list
foreach (String word in name2convert)
{
Console.WriteLine(word);
}

Related

Making a simple change function for a database app C#

Sorry if this is an ultra beginner question but, I need to be able to change all field values except the item number by giving its item number not array index. I already have a add and delete feature.
using System;
struct ItemData
{
public int ItemNumber;
public string Description;
public double PricePerItem;
public int QuantityOnHand;
public double OurCostPerItem;
public double ValueOfItem;
}
class Program
{
public static void Main()
{
int invItems = 0;
var items = new ItemData[10];
while (true)
{
Console.Write("1. Add, 2. Change, 3. Delete, 4. List:");
string strx = Console.ReadLine();
var choice = int.Parse(strx);
Console.WriteLine();
switch (choice)
{
This is what I have so far but not sure where to start
case 2: //change items
{
Console.Write("Please enter an item ID No:");
string input = Console.ReadLine();
int changeItemNumber = int.Parse(input);
bool foundItem = false;
for (int x = 0; x < invItems; x++)
{
if (items[x].ItemNumber == changeItemNumber)
{
//code
}
}
if (!foundItem)
{
Console.WriteLine("Item {0} not found", changeItemNumber);
}
break;
}
It's still a little unclear what you're asking so if this is wide of the mark then feel free to let me know.
Start by mapping out the flow of the process and then implement one piece at a time. Here's a basic series of operations you'll want to do, not necessarily in this order:
Input ItemNumber.
Find index of matching record in array.
If not found report error and stop.
Get record from user.
Set ItemNumber in record to entered value.
Store record in array at same index as original.
If you think about the way the rest of the program works you should see that some of those parts - maybe most of them - are already done somewhere in your code. Your add operation probably already has the Get record from user code. Your delete operation probably has Input ItemNumber and Find index of matching record in array done already.
So pull those parts out into methods and reuse them where it makes sense. Anywhere you're writing the same code multiple times with minor changes try to see if you can extract the code into a small method you can call with maybe some parameters. Your "input a number" code for instance - used for operation selection, item number entry and presumably whatever you're doing for delete - can be pulled out to a supporting method like this one:
static int InputNumber(string prompt)
{
Console.Write($"{prompt}: ");
var inputText = Console.ReadLine();
return int.Parse(inputText);
}
Now when you want to change the way you're doing number input you have a central place to make the changes and you don't have to worry about tracking down all the places you wrote the same code.
The same goes for the rest of the pieces. When two operations share some of the same code then pull that code out to supporting methods. Finding the index of an item in the array by some criteria can - and should - be one of those:
// Return array index of matching item or -1 if not found
int ItemIndex(int itemNumber)
{
for (int i = 0; i < invItems; i++)
{
if (items[i].ItemNumber == itemNumber)
return i;
}
return -1;
}
Likewise the code - whatever that looks like - that your add operation uses to get a record from the user.
Once you do that your change item case looks a lot simpler:
case 2: // change items
var itemNumber = InputNumber("Please enter an item ID");
var index = ItemIndex(itemNumber);
if (index == -1)
{
Console.WriteLine($"Item {itemNumber} not found.");
}
else
{
var newItem = InputItemData();
newItem.ItemNumber = itemNumber;
items[index] = newItem;
}
break;
For bonus points you can actually provide the current values to the InputItemData method so the user can re-use them instead of just asking for a complete new record each time.

How to iterate through multiple variables?

I'd like to create a short program to download several pictures from a website.
On a form, I would like to enter a root-link to a website with placeholders.
The placeholders can be defined with Start/End value and asc/desc.
For example: the original link is
google.de/1236-01.jpg
and I'd like to generate all links from
google.de/1236-1.jpg
up to
google.de/9955-12.jpg
So my input would be "google.de/[0]-[1].jpg" and placeholders are set to:
[0] = start 1236|end 9955|asc
[1] = start 1|end 12|asc
Via GetValidCharacters() I get a String-List of valid combinations for each entered placeholder (can be selected via ascending/descending + start&end).
The goal I'm struggling with is to build all combinations of this link, because I need to determine while runtime, how much placeholders I have.
My idea was to loop over an queue and enquueue each new build line, until there is none left with placeholders, but I don't know how to do this.
I need to make sure that all combinations are entered and they are entered only once.
private static void CreateDownloadList()
{
Queue<string> tmpQueue = new Queue<string>(); //temp queue
tmpQueue.Enqueue(DL_path); //DL_Path = google.de/[0]-[1].jpg
string line = "";
while ((line = tmpQueue.Dequeue()) != null) //not empty
{
if (line.Contains("[")) //placeholder
{
string tmpLine = line;
//how to determine, which placeholder is next?? need to know this and replace this with every combination, I get from GetValidCharacters(start, end, DESC)
}
else //done
{
_urlList.Add(line);
}
}
}
how about a simple for loop?
for (int i = 1236; i <= 9955; i++)
{
for (int j = 1; j <= 12; j++)
{
tmpQueue.Enqueue(string.Format("google.de/{0}-{1}.jpg", i, j));
}
}
I'm not going give you the full code but here is some pseudo code that would solve the problem.
given :
todostack -- stack object that holds a list of unresolved items
replace_map -- map object that holds marker string and map of all values
marker_list -- list of all markers
final_list -- list object that holds the results
(note you can probably use marker_list and replace_map in one object -- I have them separate to make my code clearer)
init :
push todostack with your starting string
set marker_list and replace_map to correct values (from parameters I assume)
clear final_list
algorithm :
while (there are any items in todostack)
{
curitem = todostack.pop
if (curitem contains a marker in marker_list)
{
loop for each replacement in replace_map
{
new_item = curitem replaced with replacement
todostack.push(new_item)
}
}
else
add curitem to final_list
}
#Hogan this was the hint to the correct way.
solution is this
private void CreateDownloadList()
{
Queue<string> tmpQueue = new Queue<string>();
tmpQueue.Enqueue(downloadPathWithPlaceHolders);
while(tmpQueue.Count > 0)
{
string currentItem = tmpQueue.Dequeue();
bool test = false;
if(currentItem.Contains("["))
{
foreach(Placeholder p in _placeholders)
{
if(currentItem.Contains(p.PlaceHolder))
{
foreach(string s in p.Replacements)
{
tmpQueue.Enqueue(currentItem.Replace(p.PlaceHolder, s));
}
test = true;
}
if(test)
break;
}
}
else
{
_downloadLinkList.Add(currentItem);
}
}
}

A few problems with c# : the program doesn't read files from my array, having trouble with line.split

so I'm having trouble with the program recognizing the values of my array elements (The name 'a' does not exist in the current context) , plus i can't get line.split to work(I need it to read the next element after the ',' and it needs to loop for all books (it's a library program). Lastly i can't figure out how to change the "10" (i put the number at random, so it doesn't show me an error) in my for loop, so that the program stops after it read all the info from .txt. Here's the code:
EDIT : It doesn't show any more errors, it just crashes now. :(
using System;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
foreach (string line in File.ReadAllLines(#"Duomenys.txt"))
{
string[] a = line.Split(',');
int ISBN = int.Parse(a[0]);
string BookName = a[1];
string Author = a[2];
string Genre = a[3];
string Publisher = a[4];
int PublishYear = int.Parse(a[5]);
int PageNumber = int.Parse(a[6]);
Console.WriteLine(PublishYear);
Console.WriteLine();
Console.ReadKey();
}
}
public void BookWithTheMostPages(int[] a)
{
int maxPages = 0;
string[] lines = File.ReadAllText(#"Duomenys.txt").Split('\n');
foreach (string line in lines)
{
{
Console.ReadLine();
if (a[6] > maxPages)
{
maxPages = a[6];
Console.WriteLine("Storiausios knygos pavadinimas: {0} , jos autorius(-ė): {1}", a[1], a[2]);
}
}
}
}
public void Publish(string[] a)
{
if (!File.Exists(#"Technologija.csv"))
File.Create(#"Technologija.csv").Dispose();
using (StreamWriter streamwrite = new StreamWriter(File.OpenWrite(#"Technologija.csv")))
{
if (a[2] == "Technologija")
{
streamwrite.WriteLine("\n ISBN : {0}, Pavadinimas: {1}, Autorius: {2}, Tipas: {3}, Leidykla: {4}, Išleidimo Metai: {5}, Puslapių skaičius: {6}", a[0], a[1], a[2], a[3], a[4], a[5], a[6]);
}
}
}
public void Output(string[] a)
{
if (!File.Exists(#"Autoriai.csv"))
File.Create(#"Autoriai.csv").Dispose();
using (StreamWriter streamWriter = new StreamWriter(File.OpenWrite(#"Autoriai.csv")))
{
streamWriter.WriteLine("\n{0}", a[2]);
}
}
public void Publishyear(string[] a)
{
if (a[5] == "2014")
{
for (int j = 1; j <= 5; j++)
Console.WriteLine("\nKnygos ISBN: {0}, Pavadinimas {1}, Autorius {2}", a[0], a[1], a[2]);
}
}
}
}
Here's the .txt example:
9781408855669, Harry Potter and the Chamber of Secrets, Joanne K Rowling, Apysaka, Bloomsbury Publishing PLC, 1998, 270. (It's one line)
a and line are scoped to the static Main method (well, actually a is defined twicein Main, which isn't legal). They do not exist outside of there, unless you make them available, either by passing them in as parameters, or by making them available via fields. You should probably:
come up with more meaningful names; a will not help you
pass the value in as a parameter (IMO this would be cleaner than fields, but fields would work too)
decide whether you are working in instance or static context - at the moment you have both, but never instantiate an object, so you won't be able to call any of the methods
Note that the using and foreach should not be terminated like that ; you probably meant:
foreach (string line in File.ReadAllLines(#"Duomenys.txt"))
{
string[] a = line.Split(',');
...
}
(no need for the using / StreamReader)
'a' only exists in the main function. Like Marc said, you'll want to pass in 'a' as a parameter if you're using it in a different function.
So first line of the function:
public void BookWithTheMostPages() {
}
Should be:
public void BookWithTheMostPages(string[] a)
And should be called in the main function like this:
BookeWithTheMostPages(a);
That-a-ways the function "knows" what 'a' is.
Also, I notice that you're not telling your Main function to run any of the functions you wrote. The program runs everything inside the Main function, not just everything in the Main.cs file. So your 'Publishyear', 'Output', 'Publish', and 'BookWithTheMostPages' function simply aren't running.
Now in regards to your Split function not working here's 2 things:
You have already have something name 'a' in your program, you cannot name another variable by the same name. Make sense?
You must 'Split' into another array, since Split returns a series of strings
So it should look like this:
string[] splitLine = line.split(',');
Also these to lines are not correct:
int PublishYear = Convert.ToInt32(a[5]);
int PageNumber = Convert.ToInt32(a[6]);
If you're wanting to have the 'PublishYear' and 'PageNumber' functions to return an int, they cannot be void functions.
public int Publishyear() {
/*Write your code in here*/
return year;
}
Then later you can use the Function like this to get a value.
int i = Publishyear();
Same goes for your 'PageNumber' Function.
There are still a lot of little errors in the program I haven't mentioned and it would take forever to write down everyone with an explination, but for a beginner like yourself take it piece by piece. Follow a guideline like this:
Write down what the program is supposed to do on paper.
Write a small portion of code (couple lines)
Test it.
Repeat steps 2 and 3 until finished.
One last thing, get in the habit of naming your variables with more descriptive names. 'a' doesn't let a reader know at a glance what 'a' is. Write code that is easy for other people to read. I know at the beginning programming can seems very hard and confusing, but keep at it, don't give up. And little by little you'll get this whole programming things figured out.
Cheers!
Alright so first of all, remove the
using (StreamReader dn = new StreamReader(#"Duomenys.txt"));
if you are not using it. If you are reading the file with File.ReadAllLines you are not going to need it. Also, you are not using your foreach loop correctly. The way you want to go would be something like this:
foreach (string line in File.ReadAllLines(#"Duomenys.txt"))
{
string[] a = line.split(',');
int ISBN = Convert.ToInt32(a[0]);
string BookName = a[1];
string Author = a[2];
string Genre = a[3];
string Publisher = a[4];
int PublishYear = Convert.ToInt32(a[5]);
int PageNumber = Convert.ToInt32(a[6]);
}
What I fixed aswell is that you first create a string array named a, but then create a normal string named a which does not work. Also no need to set a size for the array, string.Split() does this automatically.
EDIT: To loop the file lines, assuming they are seperated by line terminators, you could do this:
string[] lines = File.ReadAllText(filename).Split('\n');
// '\n' as the regular line terminator
foreach (string line in lines)
{
// Your other code ...

C# Format list items with BAR between words

My code is currently busted and I am aware of this. I'm working one one part at a time and I have hit two stumbling blocks which I'm hoping to find help here in regards too.
I am trying to address my formatting issue with this question here.
With the code below, i read in a text file using StreamReader, and the selections come in all on the same line as I want them too seperated by a BAR ("|"). Unfortunately, the bar prints at the end of each word, not actually 'between' each word. I don't want the last bar to print. I know i could cheat and add a bar to the font with a Console.Write("|") but that would be cheating in my mind - i wouldn't really be printing/displaying a bar between the words as I was trying to make a more elegant console selection.
This is just something I'm doing to learn and is not part of our assignment, but i like to push myself when I can. I am very very new to attempting to code, I am a complete newb, please assume I know nothing and please know all help is very much appreciated.
THIS IS MY CODE THUS FAR:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;// Needed for Streaming...
using System.IO;// Needed for Streaming...
namespace a090___StreamReader_DictionarySearch
{
class Program
{
private const String FILE_NAME = "dictionary.txt";//establish text file instance
public void Play()
{
do
{
DisplayTitle();
List<Listing> items = LoadListings();//create a list of WordDef objects
int count = 0;
foreach (Listing myListing in items)//read in items from file
{
//Console.WriteLine(myListing.GetName() + ": " + myListing.GetDefinition());
Console.Write(myListing.GetName());
if (count != items.Count - 1)
{
Console.Write(" | ");
}
count++;
}
DisplayText("\n\nPlease enter a word from the selections about to see it's definition");// Nice use of PROMPT
String userSelection = Console.ReadLine().ToLower();//Capture input
/// What are we trying to do?
/// Collect value entered for comparison - chek!
///
/// Compare value entered against list (Does value match to name?)
/// IF value matches print description
/// if value does not match(Else), state no match
//if (userSelection == Listing.name)
//{Console.WriteLine("You selected: " + userSelection() +
// "\nWhich Means: " + Listing.GetDefinition());}
//else{Console.WriteLine("I'm sorry, I don't have a match for that.");}
} while (PlayAgain());
Salutation();
}
//ToolBox -- my program specific tools
public List<Listing> LoadListings()//load entries display as list
{
StreamReader fileIn = new StreamReader(FILE_NAME);
List<Listing> entry = new List<Listing>();
//loop through every line of the file
while (!fileIn.EndOfStream)
{
String line = fileIn.ReadLine();
String[] pieces = line.Split(':');
if (pieces.Length < 1) continue;//error handling - set to length of text items
Listing myListing = new Listing(pieces[0], pieces[1]);
entry.Add(myListing);
}
fileIn.Close(); return entry;
}
//MaxBox -- my useful tools
public void DisplayText(String StringNameIs)
{ Console.WriteLine(StringNameIs); }//Where are we?
public Boolean PlayAgain()
{
Console.Write("\n\nDo you select again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
public void Salutation()
{ Console.Clear(); Console.WriteLine("Ti Do - oh - oh Ti Do -- So Do!"); } //The last line from the 'do-re-mi' song from the Sound of Music
public void DisplayTitle()
{ Console.Clear(); Console.WriteLine(">>>-- A Dictionary of Sounds --<<< \n"); } //Announce Our Program
static void Main(string[] args)
{
Program DictionaryLookup = new Program();
DictionaryLookup.Play();
Console.Read();
}
}
}
Please note: I have searched StackOverflow, GOOGLE, BING, MS' resources, et al. for an answer i can understand with my limited skills/understanding. I've also been working on this for a few hours. Please help.
You're looking for string.Join. Replace the whole foreach loop
foreach (Listing myListing in items)//read in items from file
{
//Console.WriteLine(myListing.GetName() + ": " + myListing.GetDefinition());
Console.Write(myListing.GetName() + " | ");
}
with
Console.Write(string.Join(" | ", items.Select(x => x.GetName())));
Alternatively, you could try a writing a backspace to the console.
Edit: As noted in the comments, you'd need to print a space char over the last pipe.
Console.Write("\b \b");
You may convert List of objects to array of object property and cast it to a string with delimeter:
string str = String.Join(" | ", items.Select(x => x.GetName()).ToArray());
try something like this...
var items = LoadListings();//create a list of WordDef objects
int i = 1;
var sw = new StringBuilder();
foreach(var myListing in items)
{
sw.AppendFormat("{0}", myListing.GetName() + "|");
if (i=items.Count)
{
sw.Replace("|", "", i,i);
}else
{ i++; }
}
//Console.WriteLine(myListing.GetName() + ": " + myListing.GetDefinition());
Console.Write(sw);
List<Listing> items = LoadListings(); //create a list of WordDef objects
int checklast = 0;
foreach (Listing myListing in items) //read in items from file
{
if (checklast == items.Count-1)
{
Console.Write(myListing.GetName());
}
else
{
//Console.WriteLine(myListing.GetName() + ": " + myListing.GetDefinition());
Console.Write(myListing.GetName() + " | ");
}
++checklast;
}
You can use the lazy method by checking when the last item will come so you make sure won't add BAR at the end.

C#: Get an integer representation of a string array

I am new to C# and I ran into the following problem (I have looked for a solution here and on google but was not successful):
Given an array of strings (some columns can possibly be doubles or integers "in string format") I would like to convert this array to an integer array.
The question only concerns the columns with actual string values (say a list of countries).
Now I believe a Dictionary can help me to identify the unique values in a given column and associate an integer number to every country that appears.
Then to create my new array which should be of type int (or double) I could loop through the whole array and define the new array via the dictionary. This I would need to do for every column which has string values.
This seems inefficient, is there a better way?
In the end I would like to do multiple linear regression (or even fit a generalized linear model, meaning I want to get a design matrix eventually) with the data.
EDIT:
1) Sorry for being unclear, I will try to clarify:
Given:
MAKE;VALUE ;GENDER
AUDI;40912.2;m
WV;3332;f
AUDI;1234.99;m
DACIA;0;m
AUDI;12354.2;m
AUDI;123;m
VW;21321.2;f
I want to get a "numerical" matrix with identifiers for the the string valued columns
MAKE;VALUE;GENDER
1;40912.2;0
2;3332;1
1;1234.99;0
3;0;0
1;12354.2;0
1;123;0
2;21321.2;1
2) I think this is actually not what I need to solve my problem. Still it does seem like an interesting question.
3) Thank you for the responses so far.
This will take all the possible strings which represent an integer and puts them in a List.
You can do the same with strings wich represent a double.
Is this what you mean??
List<int> myIntList = new List<int>()
foreach(string value in stringArray)
{
int myInt;
if(Int.TryParse(value,out myInt)
{
myIntList.Add(myInt);
}
}
Dictionary is good if you want to map each string to a key like this:
var myDictionary = new Dictionary<int,string>();
myDictionary.Add(1,"CountryOne");
myDictionary.Add(2,"CountryTwo");
myDictionary.Add(3,"CountryThree");
Then you can get your values like:
string myCountry = myDictionary[2];
But still not sure if i'm helping you right now. Do you have som code to specify what you mean?
I'm not sure if this is what you are looking for but it does output the result you are looking for, from which you can create an appropriate data structure to use. I use a list of string but you can use something else to hold the processed data. I can expand further, if needed.
It does assume that the number of "columns", based on the semicolon character, is equal throughout the data and is flexible enough to handle any number of columns. Its kind of ugly but it should get what you want.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication3
{
class StringColIndex
{
public int ColIndex { get; set; }
public List<string> StringValues {get;set;}
}
class Program
{
static void Main(string[] args)
{
var StringRepresentationAsInt = new List<StringColIndex>();
List<string> rawDataList = new List<string>();
List<string> rawDataWithStringsAsIdsList = new List<string>();
rawDataList.Add("AUDI;40912.2;m");rawDataList.Add("VW;3332;f ");
rawDataList.Add("AUDI;1234.99;m");rawDataList.Add("DACIA;0;m");
rawDataList.Add("AUDI;12354.2;m");rawDataList.Add("AUDI;123;m");
rawDataList.Add("VW;21321.2;f ");
foreach(var rawData in rawDataList)
{
var split = rawData.Split(';');
var line = string.Empty;
for(int i= 0; i < split.Length; i++)
{
double outValue;
var isNumberic = Double.TryParse(split[i], out outValue);
var txt = split[i];
if (!isNumberic)
{
if(StringRepresentationAsInt
.Where(x => x.ColIndex == i).Count() == 0)
{
StringRepresentationAsInt.Add(
new StringColIndex { ColIndex = i,
StringValues = new List<string> { txt } });
}
var obj = StringRepresentationAsInt
.First(x => x.ColIndex == i);
if (!obj.StringValues.Contains(txt)){
obj.StringValues.Add(txt);
}
line += (string.IsNullOrEmpty(line) ?
string.Empty :
("," + (obj.StringValues.IndexOf(txt) + 1).ToString()));
}
else
{
line += "," + split[i];
}
}
rawDataWithStringsAsIdsList.Add(line);
}
rawDataWithStringsAsIdsList.ForEach(x => Console.WriteLine(x));
Console.ReadLine();
/*
Desired output:
1;40912.2;0
2;3332;1
1;1234.99;0
3;0;0
1;12354.2;0
1;123;0
2;21321.2;1
*/
}
}
}

Categories

Resources