LINQ; Select Groups of Lines from a Text File - c#

Greeting Gurus, I have a text file with groups of text that I need to seperate into seperate string arrays. How do I group these using the line "start:" as the delimiter? (groups may contain differing line counts but the all begin with "start:". Is this a job that LINQ can accomplish? (Each line has seperate data, it does not look that way in the preview).
List<string> lines = File.ReadAllLines(#"C:\test.txt").ToList();
start: data 1
boy: data 2
great: data 3
start: data 7
boy: data 8
great: data 9
girl: data 10

may be there is a linq solution but when you simply can handle this with for loops, I think there isn't any need to linq, for example I think bellow code done what you want:
var groups = new List<List<string>>();
foreach (var line in lines)
{
if (line.StartsWith("Start:"))
{
groups.Add(new List<string>());
}
groups[groups.Count - 1].Add(line);
}
I'd assumed first line of your file starts with Start: else you should skip first lines until reach the first start:.

File.ReadAllText(#"C:\test.txt").split("start:");
Will read the file and split the file into an aray of string on the start: tag.

Related

Delete a line/row from a csv file based on line number , in C#

I have a CSV file with multiple lines , and it's loading the csv file contents into a dataGridView, now I am trying to delete a certain line based on user input, let say on the windows form app user inputs 5 in the text field and clicks the button how do I go about deleting the 5th line from the csv file ?
I am quite New in C# coding and I tried searching for a way but couldnt find anything which could help delete a line from csv based on line number.
Edit 1:
Csv file looks something like this :
Sym,Size,Direction,Action
asd,25,UP,Add to Watchlist
dsa,35,Dn,Add to Watchlist
tewer,35,UP,Add to Watchlist
few,35,Dn,Add to Watchlist
qwe,35,UP,Add to Watchlist
wer,35,Dn,Add to Watchlist
ewr,35,UP,Add to Watchlist
From the posted CSV, it looks very simple. If no individual field (something between two commas; your example data has 4 fields: Sym,Size,Direction,Action) contains a newline then you don't need to over engineer a solution. Something like this would suffice:
var lines = File.ReadAllLines("path");
var without = int.Parse(whichLineToRemoveTextbox.Text);
var first = lines.Take(without);
var second = lines.Skip(without +1);
var complete = first.Concat(second);
File.WriteAllLines("new path", complete);
If we read all the lines in, and then the user enters a 5, we Take(5) of the lines, which is 1 line of header and 4 lines of data. We then run another op that Skips n+1 lines, so we skip 6, which is 1 line of header and 5 lines of data, and start from the 6th line. We write the whole lot to file and all on we've lost the 5th line, as requested

Read Text with conditions

sample1.txt
ID Name Age
1 Amila 31
2 Jaya 28
3 Sahan 24
4 Ishara 21
This is my sample1.text file with 3 columns. I want to read the file and write only persons with age greater than 25.
Can you please help to with the best way to do this.
Thanks
Use the string.Split method to add your elements to an array or list.
For for tabs it'd look like yourString.Split("\t") and for commas yourString.Split(",")
More info on the Split here: https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8
How I would tackle this
Read the lines from the sample file using File.ReadAllLines(#"FilePath") and store them in a list.
Create a StreamWriter for writing the values you want to the Output File
If you want the headers in the output file then write the headers and then remove them from the list.
Have a loop that will split the line with line.split('\t'), check the age for that line, and write the line if it matches the condition using output.writeline("Stuff to write")
After Looking at Your Progress
Move the using(var writer=new StreamWriter(WritePath)) to above string s =""; since you are only writing the last line of the original file.
You are basically overwriting the file with each line read instead of appending.
Inside the while loop you can check the age and then write the lines you want in the format you want.

Reading All contents of a text document line by line

I have a text document with multiple lines which contain a persons name, age, favourite number and their favourite activity.
For example:
Line 1: Josh 30 100 Likes to play soccer.
Line 2: May 21 3 Likes to dance.
etc.
I have a message box which I would like to show their name, age, favourite number and activity one by one.
How can I do this and how can I pick up their number as integers too? thanks.
Sorry I have no code as I don't know what to do but I was thinking of using streamreader.
Here are the tools you need for your task:
For reading the lines of the file (Blorgbeard's suggestion):
string[] lines = File.ReadAllLines("file.txt");
For getting the values of each line (assuming that the names can be one-word only):
string[] values = line.Split(new char[]{' '},4);
For converting a value from String to Integer:
int intValue = Convert.ToInt32(strValue);

How do I break a string into an array (or List) in C#?

Using C# (VS 2010 Express) I read the contents of a text file into a string. The string is rather long but reliably broken up by "\t" for tabs and "\r\n" for carriage returns/newlines.
The tabs indicate a new column of data, and new line indicates a new row of data.
I want to create an array or List of dimensions (X)(Y) such that each spot in the array can hold 1 row of data from the text file, and all of the Y columns contained in that 1 row ("\t" means a new column of data, and "\r\n" means a new row of data").
To make things simple let's say my text has 10 rows of data, and 2 columns. I'd like to create an array or List or whatever you think is best to store the data. How do I do this? Thanks.
This is the code that I used to read the data in the text file into a string:
// Read the file as one string.
System.IO.StreamReader myFile = new System.IO.StreamReader("f:\\data.txt");
string myString = myFile.ReadToEnd();
Just as is (you already have a string with everything):
str.Split(new string[]{"\r\n"}, StringSplitOptions.None)
.Select(s => s.Split('\t'));
Gives you an IEnumerable<string[]> producing variantes like list of list, array of array and so on just needs the suitable ToArray() or ToList() etc.
However, if you can deal with each line one at a time, you can be better off with something that lets you do so:
public IEnumerable<string[]> ReadTSV(TextReader tr)
{
using(tr)
for(string line = tr.ReadLine(); line != null; line = tr.ReadLine())
yield return line.Split('\t');
}
Then you only use as much memory as each line needs. We could go further and change the reading to emit each individual cell one at a time, but this is normally enough to read files of several hundred MB in size, with reasonable efficiency.
Edit based on comments on question:
If you really wanted to, you could get a List<string[]> from:
var myFile = new StreamReader("f:\\data.txt");
var list = ReadTSV(myFile).ToList();
Alternatively, change the line yield return line.Split('\t'); to yield return line.Split('\t'); and you get a List<List<string>>.
However, if possible then work on the results directly, rather than putting it into a list first:
var myFile = new StreamReader("f:\\data.txt");
var chunks = ReadTSV(myFile);
foreach(var chunk in chunks)
{
DoSometingOnAChunk(chunk[0], chunk[1]);
}
It'll use less memory, and get started faster rather than pausing to read the whole thing first. Code like this can merrily work its way through gigabytes without complaint.
String.Split
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
File.ReadLines(sourceFilePath)
.Select(line => line.Split('\t'))
.ToArray();
This will read the file and create a list of string arrays for you
List<string[]> rows= File.ReadLines("PathToFile")
.Select(line=>line.Split('\t')).ToList();
If you want string[][] version, simply use ToArray(); instead of ToList(); at the end.
The TextFieldParser is a fantastic class for dealing with text based delimited files. You can provide it a file, a delimiter (in this case "\t") and it will provide a method to get the next line of values (as a string array).
It has advantages over a simple Split in the general case as it can handle comments, quoted fields, escaped delimiters, etc. You may or may not have such cases, but having all of those awkward edge cases handled pretty much for free is rather nice.
var result = contents.Split("\r\n".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(s => {
s.Split('\t').ToList();
}).ToList();
result will be a List<List<String>>.

Editing specific lines in a text file using c#

I'm currently trying to edit a text file in c#. This text file is created in a previous form and consists of the following :
Date Of Birth = 01/01/1980
Age = 31
Total = 40985
required1 =
required2 =
required3 =
This text file is only 13 lines long, basically i want to ignore the first three lines then edit the following 10 lines. I tried initially with the following code but the obvious flaw is appending to the file:
List<string> newlines = new List<string>();
newlines.Add(Convert.ToString(required1));
newlines.Add(Convert.ToString(required2));
newlines.Add(Convert.ToString(required3));
System.IO.File.AppendAllLines(filepath);
I'm thinking using streamreader reading all the lines but how to edit the 3rd line onwards is something of a mystery, yes I'm new using c# any help is greatly appreciated.
Since your file is small, you can load it whole into memory. Then work with that and save it, completely overwriting the whole file:
string[] lines = File.ReadAllLines(fileName);
// modify the lines
File.WriteAllLines(fileName, lines);

Categories