I am trying to make an array that will gather all the lines in all the files in a directory, I thought I had it finally, but when the string array gets to entry 111 it crashes with an IndexOutOfRangeException
string[] WordList = new string[AdjectiveListLength];
Console.WriteLine("Length .. " + AdjectiveListLength);
Console.WriteLine("String Length .. " + WordList.Length);
int o = 0;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
{
Console.WriteLine(s + " .. " + i + " .. " + o);
WordList[o] = s;
//o += 1;
}
}
The exception points to the int I commented out when I get the error, I've been trying to get this for a few hours and I've finally gotten this far I feel like I'm 1 inch from the finish line but I can't figure out what's going on.
The best way for this task is to use a List<string> that could be used without knowing beforehand the length of each file in your FileEntries array
List<string> WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadLines(FileEntries[i]).ToList();
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
// If you want also the line number then you could just use normal for..loop and C# 6.0 syntax
for(int o = 0; o < WordList.Count(); o++)
Console.WriteLine($"File:{i} at line {o} is ..{WordList[o]}");
}
If you really want to use arrays then you don't need to dimension the array because File.ReadAllLines already creates the array for you
string[] WordList = null;
for (int i = 0; i < FileEntries.Length; i++)
{
WordList = File.ReadAllLines(FileEntries[i]);
foreach (string s in WordList)
Console.WriteLine(s + " .. " + i);
}
Related
I am creating text file with 50 rows, each row have information about files. Words in row are separated by ';'. I need to sort files with bubble-sort algorithm by file size, it is third word, and write rows from file sorted in console. That means first row will have biggest file size, second, third, etc...
So far I have this:
Random rnd = new Random();
if (!File.Exists(#"C:\Users\ariak_000\Desktop\Řadící algoritmy\database\alpha.txt")) //C:\Users\bartbo13it\Downloads\alpha.txt
{
string[] arrayx = new string[50];
string[] arrayy = arrayx.Select(ggg => String.Join(";", new string[] { #"C:\user\directory", "file" + rnd.Next(100, 999), rnd.Next(0, 999999).ToString(), "txt", rnd.Next(0, 1).ToString() })).ToArray();
File.WriteAllLines(#"C:\Users\ariak_000\Desktop\Řadící algoritmy\database\alpha.txtt", arrayy);
}
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\ariak_000\Desktop\Řadící algoritmy\database\alpha.txt");
int pocet_radku = File.ReadAllLines(#"C:\Users\ariak_000\Desktop\Řadící algoritmy\database\alpha.txt").Length;
List<int> velikostsouboru = new List<int>();
using (StreamReader sr = new StreamReader(#"C:\Users\ariak_000\Desktop\Řadící algoritmy\database\alpha.txt"))
{
Console.WriteLine("Pocet radku " + pocet_radku);
for (int i = 0; i < pocet_radku; i++)
{
string radek = sr.ReadLine();
string[] rozdeleni = radek.Split(';');
int ParsePokus = Int32.Parse(rozdeleni[2]);
velikostsouboru.Add(ParsePokus);
}
}
int[] array = velikostsouboru.ToArray();
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 0; j < array.Length - i - 1; j++)
{
if (array[j + 1] > array[j])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for (int a = 0; a < array.Length; a++)
{
Console.WriteLine(array[a] + " ");
}
Console.ReadKey();
It just sorts file size with bubble-sort algorithm and writes file sizes in console sorted from biggest to smallest. Still need to write whole lines sorted, not just file size.
I will appreciate any help.
// There are better ways to create a file, but I decided to keep it in the original.
const string filePath = #"C:\Users\ariak_000\Desktop\Řadící algoritmy\database\alpha.txt";
var rnd = new Random();
if (!File.Exists(filePath))
{
var array = new string[50].Select(x => String.Join(";", new[]
{
#"C:\user\directory",
"file" + rnd.Next(100, 999),
rnd.Next(0, 999999).ToString(CultureInfo.InvariantCulture),
"txt",
rnd.Next(0, 1).ToString(CultureInfo.InvariantCulture)
})).ToArray();
File.WriteAllLines(filePath, array);
}
// It will read the file and fill a variable with the data
// Convert the value to int is necessary in the order process
// Otherside, it will consider 9 higher than 10.
var data = File.ReadAllLines(filePath)
.Select(value => value.Split(';'))
.Select(x => new
{
Folder = x[0],
FileName = x[1],
Size = Convert.ToInt32(x[2]),
Extension = x[3],
IsActive = x[4]
})
.ToList<dynamic>();
// You can change it using the bubble sort as you wish
// I preffer the linq way.
var orderedData = data.OrderByDescending(x => x.Size);
// Writes the header in console (du~)
Console.WriteLine("Folder" + "\t\t\t"
+ "FileName" + "\t"
+ "Size" + "\t"
+ "Extension" + "\t"
+ "IsActive");
foreach (var result in orderedData)
{
// If you want to write the result in a file, you do it here.
Console.WriteLine(result.Folder + "\t"
+ result.FileName + "\t\t"
+ result.Size + "\t"
+ result.Extension + "\t\t"
+ result.IsActive);
}
Console.ReadKey();
I don't know how to get the first rows of a first foreach run with the first rows of a second foreach.
The second rows of a first foreach run with the second rows of the second foreach.
Because I get all data into List<> and the foreach two list.
My code like:
for (int i = valuesFrom; i < valuesTo; i++)
{
values = name + " " + i;
lstAliasImage.Add(values);
}
for (int j = 0; j < lstImgAdded.Items.Count; j++)
{
string imgPath = lstImgAdded.Items[j].Text;
lstNameImage.Add(imgPath);
}
foreach (var alias in lstAliasImage)
{
foreach (var items in lstNameImage)
{
txtUser.Text = alisa;
Save(items + " " + txtUser.Text);
}
}
You can do that with a good old for cycle:
for (int i = 0; i < lstAliasImage.Count; i++) {
txtUser.Text = listAliasImage.ElementAt(i);
Save(lstNameImage.ElementAt(i) + " " + txtUser.Text);
}
Here I assumed that by alisa you meant alias. Also, I assumed that the element count is the same. If your type has an indexer defined, then you can use [i] instead of ElementAt(i).
Using a for loop will solve your problem;
for (int i = 0; i < lstAliasImage.Count; i++)
{
txtUser.Text = lstAliasImage[i];
Save(lstNameImage[i] + " " + txtUser.Text);
}
But it is better to solve this in a different way. As both Lists are related, you should create a struct, and store that in the list. At least to avoid errors if both lists are not the same length. Something like
public struct ImageStruct
{
public String alias;
public String name;
}
List<ImageStruct> images = new List<ImageStruct>();
for (int i = valuesFrom; i < valuesTo; i++)
{
images.Add(new ImageStruct()
{
alias="alias " + i,
name="name " + i
});
}
foreach (var item in images)
{
txtUser.Text = item.alias;
Save(item.name + " " + item.alias);
}
I hope you get the idea (I did not test the above code).
I am having a problem with the following:
I am loading a file into C# and then I am splitting it by lines with this code.
// Splitting by line from original file
string[] lines = showText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
Now I need a for loop that will go through lines and get Substring from those lines, separately.
Here is what I am trying to accomplish, in a way:
for (int i = 0; i < lines.Length; i++)
{
int[] testing = new int[i];
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
The error here is: Index was outside the bounds of the array.
Here is a picture also to get better idea as to what I'm trying to do.
http://s30.postimg.org/jbmjmqv1t/work.jpg
textBox1.Text = lines[0].Substring(16,1) + " " + lines[0].Substring(23,9);
textBox1.Text = lines[1].Substring(16,1) + " " + lines[1].Substring(23,9); //etc
Could anyone help me with this?
You are creating the array in the for loop, so it is being created for each line and with the wrong length. Instead of this part of the code:
for (int i = 0; i < lines.Length; i++)
{
int[] testing = new int[i];
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
you should be doing this:
int[] testing = new int[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
testing[i] = int.Parse(lines[i].Substring(16, 1));
textBox1.Text = testing.ToString();
}
This is how I've solved it.
int[] testing = new int[lines.Length];
textBox1.Clear(); //Just to clear it if button pressed again
for (int i = 0; i < lines.Length; i++)
{
testing[i] = int.Parse(lines[i].Substring(16, 1));//just getting the needed value
textBox1.Text += testing[i].ToString() + "\r\n" ;//adding each value to textBox1, separated by new line
}
I have created a multi-dimensional array:
string[,] array_questions = new string[dt.Rows.Count, dt.Columns.Count];
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
array_questions[i, j] = dt.Rows[i][j].ToString();
//Response.Write(array_questions[i, j]);
}
// Response.Write(Environment.NewLine);
//Response.Write("\n");
}
foreach (string number in array_questions)
{
//Response.Write(number + " ");
//Response.Write(Environment.NewLine);
Response.Write(string.Join(", ", number) + Environment.NewLine);
}
but it shows an error like : Error 1 The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments.. Please help
You do not need a for loop to join the string.
string.Join(", ", array_questions)
Replace the code
foreach (string number in array_questions)
{
//Response.Write(number + " ");
//Response.Write(Environment.NewLine);
Response.Write(string.Join(", ", number) + Environment.NewLine);
}
with
Response.Write(string.Join(", ", array_questions) + Environment.NewLine);
You need to flatten your array to use string.Join. It takes the separator and a single dimensional array, so you may proabably need to do something like this. But not sure what you are trying to achieve here. You are trying to call string.Join(string, string[]) as string.Join(string, string)
Try something like this:
var sdArray= new List<string>();
for (var i = 0; i < dt.Rows.Count; i++) //Get the length of first Dimension
{
for (var j = 0; j < dt.Columns.Count; j++) //Get the length of second Dimension
{
sdArray.Add(array_questions[i, j]);
}
}
///
Response.Write(string.Join(", ", sdArray) + Environment.NewLine);
Using Linq you can flatten this in a better way.
Something like this
string joinedSetOfQns= string.Join(",",
Enumerable.Range(0, dt.Rows.Count)
.SelectMany(i => Enumerable.Range(0, dt.Columns.Count)
.Select(j => array_questions[i, j])));
Response.Write(joinedSetOfQns + Environment.NewLine);
This is the defenision for string.Join
public static string Join(
string separator,
params string[] value /// <-- Takes single Dimensional Array not a string.
)
Update: Since you need to join Rowwise
for (var i = 0; i < dt.Rows.Count; i++)
{
var result = new List<string>();
for (var j = 0; j < dt.Columns.Count; j++)
{
result.Add(array_questions[i, j]);
}
Response.Write(string.Join(", ", result) + Environment.NewLine);
}
I have tried several time but couldn’t find the way to solve my problem. Here my txt file shown in below.
695
748
555
695
748
852
639
748
I put the for loop to read the data and put them in to array. So now I want to filter repeat numbers from the input txt data. How can I have a count of repeated data.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
for (int i = 0; i < n; i++)
{
res[i] = line[i].Substring(x,x+8);
Console.WriteLine(res[i]);
}
Console.ReadLine();
}
You use GroupBy()
var result = res.GroupBy(x => x);
foreach(var g in result)
{
Console.WriteLine(g.Key + " count: " + g.Count());
}
Somehow you have to keep track of things you have seen before.
One way to do that is to place the numbers in a list the first time you see them. If a given number is already in the list, filter it out on the latter occurrences.
Here's an example with the list. Note that your code to fetch a substring of the input crashes.
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
List<string> observedValues = new List<string>();
for (int i = 0; i < n; i++)
{
string consider = line[i]; // This code crashes: .Substring(x, x + 8);
if (!observedValues.Contains(consider))
{
observedValues.Add(consider);
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
Another method is to pre-sort the input so that duplicates are adjacent.
Example:
(Note, you may want to remove white space in the input prior to sorting. Leading white space will break this code).
static void Main(string[] args)
{
int x = 0;
int count = 0;
String[] line = new string[] { "123", "456", "123" }; //File.ReadAllLines("C:/num.txt");
int n = line.Length;
String[] res = new String[n];
string previous = null;
Array.Sort(line); // Ensures that equal values are adjacent
for (int i = 0; i < n; i++)
{
string consider = line[i].Trim(); // Note leading whitespace will break this.
if (consider != previous)
{
previous = consider;
res[i] = consider;
Console.WriteLine(res[i]);
}
else
{
Console.WriteLine("Skipped value: " + consider + " on line " + i);
}
Console.ReadLine();
}
}
So now I want to filter repeat numbers from the input txt data.
if all you need is filter out duplicates you can use this:
String[] line = File.ReadAllLines("C:/num.txt");
var filteredLines = line.Distinct();
foreach (var item in filteredLines)
Console.WriteLine(item);