easiest way to take file into an array? - c# - c#

I have a file of integers. the first number - the number of subsequent numbers.
as the easiest way to take this file into an array? C#
Example 1: 8 1 2 3 4 5 6 7 8
Example 2: 4 1 2 3 0
Example 3: 3 0 0 1

int[] numbers = File
.ReadAllText("test.txt")
.Split(' ')
.Select(int.Parse)
.Skip(1)
.ToArray();
or if you have a number per line:
int[] numbers = File
.ReadAllLines("test.txt")
.Select(int.Parse)
.Skip(1)
.ToArray();

int[] numbers = File
.ReadAllLines("test.txt")
.First()
.Split(" ")
.Skip(1)
.Select(int.Parse)
.ToArray();

if your file consist of all numbers in column style (under eachother), than you can read it like this
static void Main()
{
//
// Read in a file line-by-line, and store it all in a List.
//
List<int> list = new List<int>();
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(Convert.ToInt16(line)); // Add to list.
Console.WriteLine(line); // Write to console.
}
}
int[] numbers = list.toArray();
}
ok, post was updated after i posted this, but might be of some help though :)

Related

How to remove duplicate strings with odd index line and next even string in text file and avoid it for evens

I'm trying to remove duplicate strings located only on the odd index number lines with next even line inside text document about 30 000 rows, and avoid it for even lines content, even must be removed only if it is next after odd duplicate. For example with index numbers content:
0. some text 1
1. some text 2
2. some text 3
3. some text 2
4. some text 5
5. some text 6
6. some text 2
7. some text 7
8. some text 2
9. some text 9
and must be processed this way:
some text 1
some text 2 // keep unique
some text 3
some text 2 // remove odd duplicate
some text 5 // remove even because previous is odd duplicate
some text 6
some text 2 // keep because this duplicate on even line
some text 7
some text 2 // keep because this duplicate on even line
some text 9
to get this:
some text 1
some text 2
some text 3
some text 6
some text 2
some text 7
some text 2
some text 9
But I'm not sure how get this result. So seems like I've to read all lines content, and ask for index:
if (index % 2 == 0)
{
}
but can't get, how to compare these lines to go further
Samples: Simple | Extended
Code:
string[] lines = System.IO.File.ReadAllLines("/path/to/file.txt");
List<string> newLines = new List<string>();
for(int x = 0; x < lines.Length; x++)
{
if(x % 2 == 1 && newLines.Contains(lines[x])) //is odd and already exists
x++; \\skip next even line
else
newLines.Add(lines[x]);
}
Read and Write Line by Line - Code:
//Delete file if exists
if(System.IO.File.Exists(#"/path/to/new_file.txt"))
System.IO.File.Delete(#"/path/to/new_file.txt")
List<string> newLines = new List<string>();
using (System.IO.StreamReader file = new System.IO.StreamReader(#"/path/to/file.txt"))
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"/path/to/new_file.txt", true))
{
string line = null;
int x = 0;
while((line = file.ReadLine()) != null)
{
if(x % 2 == 1 && newLines.Contains(line)) //is odd and already exists
x++; \\skip next even line
else
{
newLines.Add(line);
writer.WriteLine(line);
}
x++;
}
}
Results should be:
+EVEN: some text 1
+ODD: some text 2
+EVEN: some text 3
-ODD: some text 2
-EVEN: some text 5
+ODD: some text 6
+EVEN: some text 2
+ODD: some text 7
+EVEN: some text 2
+ODD: some text 9
Unless I'm reading your requirements incorrectly, the following should work (although I havent tested):
string[] original = System.IO.File.ReadAllLines("path/to/file");
List<string> working = new List<string>;
int i = 0;
while (i < original.Length)
{
if (i % 2 != 0)
{
// line is odd - check whether this is a duplicate
int dupeCount = working.Where(a => a == original[i]).ToList().Count;
if (dupeCount > 0)
{
// this is a duplicate - skip this AND the next line
i += 2;
continue;
}
else
{
// no duplicate found - add to list
working.Add(original[i]);
}
}
else
{
// line is even - value always gets added
working.Add(original[i]);
}
i++;
}
// List<string> working should now contain the output you want
Suppose you have List<string> all you loop them like this
var duplicates = new List<int>();
for (int i=0; i < all.Count ; i+=2)
{
if (all.FindAll(o=>o==all[i]).Count>1)
duplicates.add(i);
}
And then you remove elements marked in duplicate.

How do I read a matrix from a file into an array

Hey guys Im trying to be able to save an array from a text file but I'm at my wits end trying to figure out how to save it. I can print all the elements of the matrix as can be seen from the text file.
Sample input:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
1 2 3 4 5
I keep getting an index out of range exception. Not sure what's happening.
Hopefully you guys understand what im trying to do.
Here's what I have so far:
class Program
{
static void Main(string[] args)
{
string input =
#"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 5\Chapter 15 Question 5\TextFile1.txt";
StreamReader reader = new StreamReader(input);
List<string> list = new List<string>();
char[] unwanted = new char[] { ' ' };
using (reader)
{
int row = 0;
int column = 0;
string line = reader.ReadLine();
while (line != null)
{
string[] numbersString = line.Split(unwanted);
int[,] numbersInt = new int [ row, numbersString.Length];
foreach (string a in numbersString)
{
Console.Write("{0} ",a);// this is to check that the array was read in the right order
numbersInt[row, column] = int.Parse(a);
column++;
}
line = reader.ReadLine();
Console.WriteLine();
row++;
}
}
}
}
I suggest using jugged arrays (array of array int[][]) instead of 2D ones; in that case the solution will be quite simple, something like this (Linq):
int[][] matrix = File
.ReadLines(#"C:\myFile.txt")
.Split(new Char[] {' ', '\t'}, StringSplitOptions.RemoveEmptyEntries)
.Select(items => items
.Select(item => int.Parse(item))
.ToArray())
.ToArray();
Test (let's print out the matrix):
String report = String.Join(Environment.NewLine, matrix
.Select(line => String.Join(" ", line)));
Console.Write(report);
This change in your while should do the trick:
while (line = file.ReadLine()) != null)
{
...
}
Source: MSDN
You appear to be creating your instance of numbersInt inside your while loop. This means that with each pass of the loop you will re-create the array and when the loop exits the array will be lost. Move the declaration for numberInt to outside of the while loop.
Your immediate issue is that your code does not reset column back to zero after reading each line. Move int column = 0 into the while loop to fix this issue.
The second issue is numbersInt allocation. You create it for each line, which is not right, because it's a 2-D array. You need to create it before the loop, but of course you can't, because you don't know how many lines you are going to have. One approach is to use a dynamic data structure, and add one row at a time to it.
You can greatly simplify your code by using File.ReadAllLines method in combination with LINQ, because this would let you get rid of a lot of simple code. Now you can check how many lines you have before creating your 2-D array, and you could fill it in much easier as well:
var allRows = File
.ReadLines(#"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 5\Chapter 15 Question 5\TextFile1.txt")
.Select(line => line.Split(unwanted).Select(int.Parse).ToList())
.ToList();
If you are OK with an array of arrays, you don't need to do anything: allRows is a 2-D structure of rows and columns containing your matrix.
If you must convert it to a 2-D array, you can do it with a pair of nested for loops:
if (allRows.Count == 0) {
// ... The file has no data - handle this error
}
var matrix = new int[allRows.Count, allRows[0].Count];
for (int row = 0 ; row != allRows.Count ; row++) {
for (int col = 0 ; col != allRows[0].Count ;col++) {
matrix[row, col] = allRows[row][col];
}
}

How to split string and convert to int

Basically lets say I have used this:
string[] result = File.ReadAllText("C:\\file.txt");
Inside the .txt file is the following words/values (case sensitive):
Zack 2 5 5
Ben 5 3 4
Dom 2 4 6
Currently I know whatever is read will be stored in the string array and it includes the name and numbers.
How do I split them so that the names are in one array and the numbers are converted into int array? Basically separating the numbers and names.
Loop over each item, split by space, use the first value as a key, then use the rest of the values to create array of ints.
string[] result = { "Zack 2 5 5", "Ben 5 3 4", "Dom 2 4 6" };
var lookup = result.ToDictionary(
key => key.Split(' ').First(), // first is name, ignore rest
ints => ints.Split(' ')
.Skip(1) // skip the name, ints are the rest
.Select(i => int.Parse(i))
.ToArray());
foreach (var kvp in lookup)
Console.WriteLine(kvp.Key + " - " + string.Join(",", kvp.Value));
Output:
Zack - 2,5,5
Ben - 5,3,4
Dom - 2,4,6
I used Dictionary as the generated list. That's assuming that every item in the result array has a unique name value. If there are duplicates, you'll need to modify it to either append the new int values or use something else than a dictionary to keep your parsed values.
You can see this SO thread about the case-sensitivity of dictionaries (they arn't).
For chars array:
string charsArray = new String(result.ToCharArray().Where(c => Char.IsLetter(c)).ToArray());
For numbers array;
string NumbersArray = new String(result.ToCharArray().Where(c => Char.IsDigit(c)).ToArray());
Decide just when and how to use them. good luck
one way of use is per row.

How do I bring in numbers from a text file and do math on them in c#

I am new to C#.
I am trying to bring numbers from a txt file into my program and multiply them.
The text file would be formatted like this:
1
2
3
4
5
6
7
8
9
10
I need the program to do 1x2x3x4x5x6x7x8x9x10=3628800.
This is a list of 2 million different numbers.
I can get it to output to a text file, just not input.
I have looked around and can't really see an answer.
Thanks.
You can do this with few lines of code.
var lines = File.ReadLines(fileName);
var collection = new List<int>();
foreach (var line in lines)
{
collection.AddRange(line.Split(' ').Select(n => Convert.ToInt32(n)));
}
var result = collection.Distinct().Aggregate((i, j) => i * j); // remove distinct if you don't want eliminate duplicates.
You can try this
string value1 = File.ReadAllText("file.txt");
int res = 1;
var numbers = value1.Split(' ').Select(Int32.Parse).ToList();
for(int i=0;i<numbers.Count;i++)
{
res = res * numbers[i];
}
Console.WriteLine(res);
var numbers = File.ReadAllText("filename.txt").Split(' ').Select(int.Parse); // Read file, split values and parse to integer
var result = numbers.Aggregate(1, (x, y) => x * y); // Perform multiplication
You want to multiply 2 million numbers all together, but there is a problem.
The problem is memory limitation. to hold a big number you have to use BigInteger class inside System.Numerics namespace.
You can use this reference by adding Using keyword in top of your project.
using System.Numerics;
If the compiler did not recognize Numerics then You need to add an assembly reference to System.Numerics.dll.
Your code should look like this.
string inputFilename = #"C:\intput.txt"; // put the full input file path and name here.
var lines = File.ReadAllLines(inputFilename); // put text lines into array of string.
BigInteger big = new BigInteger(1); // create the bigInt with value 1.
foreach (var line in lines) // iterate through lines
{
big *= Convert.ToInt32(line); // Multiply bigInt with each line.
}
string outputFilename = #"C:\output.txt"; // put the full output file path and name here
File.WriteAllText(outputFilename, big.ToString()); // write the result into text file
This may take a long time to complete. but this all depends on hardware that is operating. You may get memory overflow exception during this task which depends on amount of memory you have.

Visual C# crawling through a txt file and flagging an error when value is missing

I have a txt file loaded in visual C#, lets say, for example, the text file is written like this:
"""""
1
2
3
4
5
"""""
it is counting correctly from 1-5.
now lets say I add a txt file that looks like this:
"""""
1
2
3
5
"""""
The 4 is missing from the list. Now I want an error message to popup that says, "Line 4 missing value '4'".. Or something like that. I am new to programming, and I am not expecting anyone to do my work for me, I just need a little bit of guidance as to what steps I can take and I would appreciate any help.
My txt file is being loaded into a richtextbox in VB, it displays as Plain Text.
string filename = filedialog.FileName;
textbox1.Text = filedialog.fileName;
richTextBox1.LoadFile(textbox1.Text,
richtextboxStreamType.PlainText
Assuming that all lines contain only numbers (apart from the "" at the beginning/end):
var numbers = File.ReadLines(path)
.Where(line => !string.IsNullOrWhiteSpace(line) && line.Trim().All(Char.IsDigit))
.Select(line => int.Parse(line))
.OrderBy(i => i)
.ToList();
int min = numbers.Min();
int max = numbers.Max();
var gaps = Enumerable.Range(min, max - min + 1).Except(numbers);
if(gaps.Any())
{
int firstGap = gaps.First(); // 4
string allGaps = string.Join(",", gaps);
}

Categories