convert string[] to doube[,] in C# - c#

i have text file consist of data like:
1,2
2,3
3,4
4,5
Now I want to save the data into an array. So i do split:
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
}
however my data save in string[] while I have a GlobalDataClass array declared as double[,]. Something like this:
static class GlobalDataClass
{
public static double[,] Array = new double[4, 2];
}
I need to assign the data to the GlobalDataClass:
GlobalDataClass.Array = data;
So my question is how to convert the string[] to double[,]?

Since you have a 2-d array, you'd need to iterate over each line and extract the values, then assign it into the proper position. You can use Select and double.Parse to convert the string values to double.
using (var reader = new StreamReader("file.txt"))
{
string line;
for (var count = 0; count < 4; ++count)
{
var data = reader.ReadLine()
.Split(',')
.Select(v => double.Parse(v))
.ToArray();
GlobalDataClass.Array[count,0] = data[0];
GlobalDataclass.Array[count,1] = data[1];
}
}
Now if your array was really double[][], then you could do something more like:
GlobalDataClass.Array = File.ReadAllLines("file.txt")
.Select(l => l.Split(',')
.Select(v => double.Parse(v))
.ToArray())
.ToArray();
Note: I think it's like a really bad idea to make it a global variable. There's probably a much better way to handle this.

I think that the best way is to use Array.ConvertAll.
Example:
string[] strs = new string[] { "1.00", "2.03" };
Array.ConvertAll(strs, Double.Parse);

System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
int counter =0 ;
while((line = file.ReadLine()) != null)
{
var lineData= line.Split(',');
GlobalDataClass.Array[counter,0] = double.Parse(lineData[0]);
GlobalDataClass.Array[counter,1] = double.Parse(lineData[1]);
counter++;
}

Try This:
String [] words;
int lineCount=0;
String [] Lines=File.ReadAllLines(#"C:\Data.txt");
for (int i=0;i<Lines.Length;i++)
{
words = Lines[i].Split(',');
for (int j = 0; j < 2; j++)
{
GlobalDataClass.Array[i,j] = Convert.ToDouble(words[j].Trim());
}
}

I am using some part of your code to show you how you do this task.
int mCount = 0;
using (streamreader sr = new streamreader("file.txt")) {
string[] data = sr.ReadLine().Split(',');
GlobalDataClass.Array[mCount , 0] = Double.Parse(data[0]);
GlobalDataClass.Array[mCount , 1] = Double.Parse(data[1]);
mCount += 1;
}

double[] doubleArray = strArray.Select(s => Double.Parse(s)).ToArray();
int k = 0;
for (int i = GlobalDataClass.Array.GetLowerBound(0); i <= GlobalDataClass.Array.GetUpperBound(0); i++)
{
for (int j = GlobalDataClass.Array.GetLowerBound(1); j <= GlobalDataClass.Array.GetUpperBound(1); j++)
{
double d = doubleArray[k];
GlobalDataClass.Array.SetValue(d, i, j);
k++;
}
}

If the number of lines can vary:
var lines = File.ReadAllLines("file.txt");
var data = new double[lines.Length, 2];
for (var i = 0; i < lines.Length; i++)
{
var temp = lines[i].Split(',');
data[i,0] = double.Parse(temp[0]);
data[i,1] = double.Parse(temp[1]);
}
GlobalDataClass.Array = data;
..or, if the number of lines is a constant value:
using (var sr = new StreamReader("file.txt"))
{
var i = 0;
var len = GlobalDataClass.GetLength(0);
while (sr.Peak() >= 0 && i < len)
{
var temp = sr.ReadLine().Split(',');
GlobalDataClass.Array[i,0] = double.Parse(temp[0]);
GlobalDataClass.Array[i,1] = double.Parse(temp[1]);
i++;
}
}

Related

I want to read a table from text file and assign each column to an array

i want to store each row in a different array. below is the code i tried.
but it doesn't not work, it only splits the last line and store values in "valueperline" array
first 11 rows are source text. file and screen shot of console
using System;
using System.Collections.Generic;
using System.IO;
namespace BBS_optimize
{
class Program
{
static void Main()
{
int i = 0; int j = 0; int k =0; string[] valueperline = new string[0]; string[] lines = new string [0];
lines = File.ReadAllLines("Table1.txt");
for (i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (j = 0; j<lines.Length; j++)
{ valueperline = lines[j].Split('\t');
}
for (k = 0; k < 44; k++)
{ Console.WriteLine(valueperline[k]);
}
}
}
}
Use array:
string[,] ParseFromFile (string fileName)
{
// Assume that your table have 10 cols and 100 rows
string[,] result = new string[10,100];
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
string[] row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries);
result[i] = row;
}
return result;
}
Use List:
List<List<string>> ParseFromFile (string fileName)
{
// Your list
List<List<string>> result = new List<List<string>>();
string str = File.ReadAllText (fileName);
// Split each line to arrays
string[] yourStringArray = str.Split(new[]{'\r', '\n'},StringSplitOptions.RemoveEmptyEntries);
for (int i == 0; i < yourStringArray; i++)
{
List<string> row = yourStringArray[i].Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries).ToList();
result.Add(row);
}
return result;
}
below is a solution:
static void Main(string[] args)
{
List<List<string>> lst = new List<List<string>>();
string[] lines = new string[0];
lines = File.ReadAllLines("tableX.txt");
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine(lines[i]);
}
for (int j = 0; j < lines.Length; j++)
{
var line = lines[j].Split(' ').ToList();
lst.Add(line);
}
foreach (var item in lst)
{
for (int k = 0; k < item.Count; k++)
{
Console.WriteLine(item[k]);
}
}
}

Arrange strings in alphabetical order

//code with problem (maybe)
numberArray = NameNumEquv;
listStringArray = NamesArray;
string[] sortedArray = new string[NamesArray.Length];
for (int arrayItemCounter = 0; arrayItemCounter < NamesArray.Length; arrayItemCounter++)
{
compareArrayCount = 1;
initialArrayCount = 0;
while (compareArrayCount < numberArray.Length)
{
for (int doubleArrayLength = 0; doubleArrayLength < numberArray[compareArrayCount].Length; doubleArrayLength++)
{
if (numberArray[initialArrayCount][doubleArrayLength] < numberArray[compareArrayCount][doubleArrayLength])
{
initialArrayCount = compareArrayCount;
break;
}
}
compareArrayCount = compareArrayCount + 1;
}
sortedArray[arrayItemCounter] = listStringArray[initialArrayCount];
List<string> tempArrayValues = new List<string>();
List<int[]> tempNumArrayValues = new List<int[]>();
for (int tempArrayCount = 0; tempArrayCount < listStringArray.Length; tempArrayCount++)
{
if (tempArrayCount != initialArrayCount)
{
tempArrayValues.Add(listStringArray[tempArrayCount]);
tempNumArrayValues.Add(numberArray[tempArrayCount]);
}
}
listStringArray = tempArrayValues.ToArray();
numberArray = tempNumArrayValues.ToArray();
tempArrayValues.Clear();
tempNumArrayValues.Clear();
}
//till here
foreach (string nums in sortedArray)
{
Console.WriteLine(nums);
}
}
public static int[] AlphaNumericConversion(string stringValue, int arrayLength)
{
string Alphabets = "abcdefghijklmnopqrstuvwxyz";
char[] alphabetArray = Alphabets.ToCharArray();
string lowerCaseConv = stringValue.ToLower();
char[] stringArray = lowerCaseConv.ToCharArray();
int[] numericalConvertedArray = new int[arrayLength];
for (int valueArrayCount = 0; valueArrayCount < numericalConvertedArray.Length; valueArrayCount++)
{
numericalConvertedArray[valueArrayCount] = 0;
}
for (int letterCounter= 0;letterCounter < stringArray.Length;letterCounter++)
{
for (int alphabetCounter = 0; alphabetCounter < Alphabets.Length; alphabetCounter++)
{
if (stringArray[letterCounter] == alphabetArray[alphabetCounter])
numericalConvertedArray[letterCounter] = alphabetCounter + 1;
}
}
return numericalConvertedArray;
}
}
}
I want to arrange strings in ascending order. It is arranging the single letter strings(a, b, c,d, e.....) in reverse alphabetical order as in Z-A and string containing 2 or more letters randomly such as "Aayush", "Ayush", "Aayusha", "Ayusha" to "Aayusha","Ayusha","Aayush","Ayush". What is wrong with the code. Don't suggest to simply use List.Sort() because I want to write it in algorithmic manner. I'm trying to understand how it works rather than using Sort().

How to iterate over a multidimensional string array?

I have a 2d string array (at least I think it is called a 2d array):
var target = new string[var1,var2];
Now I want to convert it to List<List<string>>:
var listlist = new List<List<string>>();
foreach (var row in target)
{
var newlist = new List<string>();
foreach (var el in row)
{
newlist.Add(el);
}
listlist.Add(newlist);
}
But row has a type is string and el has type is char.
I can't understand why el is not a string? What's wrong?
A foreach interates over a string[,] like it is a string[]. It doesn't split in rows.
If you do want to handle 'rows' and 'columns' those separately, you have to get the dimensions of the array, using the GetLength method:
var target = new string[var1, var2];
var listlist = new List<List<string>>();
for (int x = 0; x < target.GetLength(0); x++)
{
var newlist = new List<string>();
for (int y = 0; y < target.GetLength(1); y++)
{
newlist.Add(target[x, y]);
}
listlist.Add(newlist);
}
This is what you need
static void SoStrList()
{
int var1=10, var2=7;
var target=new string[var1, var2];
var listlist=new List<List<string>>();
for(int i=0; i<var1; i++)
{
var row=new List<string>();
for(int j=0; j<var2; j++)
{
row.Add(target[i, j]);
}
listlist.Add(row);
}
}
use for loop instead of foreach
var target = new string[2, 2];
target[0, 0] = "a";
target[0, 1] = "A";
target[1, 0] = "b";
target[1, 1] = "B";
var listlist = new List<List<string>>();
for (int i = 0; i < target.GetLength(0); i++)
{
var newlist = new List<string>();
for (int j = 0; j < target.GetLength(1); j++)
newlist.Add(target[i,j]);
listlist.Add(newlist);
}
Here:
foreach (var row in target)
You already have first element of your 2d array, and foreach take all chars of this elements
well ... string is array of chars.
And this confusion is what you get from using keyword var for almost everything. Its not javascript.
Secondly : You need to go for something like this
for (int i = 0; i < target.GetLength(0); i++)
{
for (int y = 0; y < target.GetLength(1); y++)
{
your manipulation with strings
}
}
but srsly... get rid of vars !!!
For LINQ lovers, the same can be achieved using the following two lines:
int R = s.GetLength(0), C = s.GetLength(1);
var MyList = Enumerable.Range(0, R).Select(i => i * C).Select(i => s.Cast<string>.Skip(i).Take(C).ToList()).ToList();

Coding in C# for complex number

how to normalize the complex numbers in c#?when i have saved the text file of complex number in notepad.then i want to use these complex numbers in my c# code.And can be read text file of complex number in c#?
Current code used:
using (TextReader reader = File.OpenText("a.txt"))
{
var lineCount1 = File.ReadLines("a.txt").Count();
x1 = new double[lineCount1, 512];
for (int i = 0; i < lineCount1; i++)
{
for (int j = 0; j < 512; j++)
{
string line = reader.ReadLine();
string[] bits = line.Split(' ');
x1[i, j] = double.Parse(bits[j]);
}
}
}
its not working.!!! error in last line.
Perhaps you should have something like this:
static void Main(string[] args)
{
var lines = File.ReadAllLines("a.txt");
var complexes = new Complex[lines.Length];
for (int i = 0; i < complexes.Length; i++)
{
complexes[i] = Parse(lines[i]);
}
}
private static Complex Parse(string s)
{
var split = s.Split(new char[' '], StringSplitOptions.RemoveEmptyEntries); // I guess string is something like "12 54". If you have "12 + 54i" you'l get an exception here
return new Complex(double.Parse(split[0]), double.Parse(split[1]));
}

pass 2d array from code behind to javascript

I have a DataTable that I get from the DB, I want to create a 2d array in the code behind (once I get the DataTable..), and then pass it as a 2d array to Javascript.
this is what I tried to code :
int[,] videoQarray = new int[dt_questionVideo.Rows.Count,dt_questionVideo.Columns.Count ];
string[,] videoQarrayTitle = new string[dt_questionVideo.Rows.Count, dt_questionVideo.Columns.Count ];
for (var i = 0; i < dt_questionVideo.Rows.Count ; i++)
{
for (int j = 0; j < dt_questionVideo.Columns.Count; j++)
{
videoQarray[i,j] = Convert.ToInt32(dt_questionVideo.Rows[i][0]);
videoQarrayTitle[i,j] = dt_questionVideo.Rows[i][1].ToString();
}
}
string createArrayScript = string.Format("var videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("var videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
Page.ClientScript.RegisterStartupScript(this.GetType(), "registerVideoQArray", createArrayScript, true);
well, in the browser console it says that videoQarray is not defined..
I wonder how can I do that properly..
Probably the variable is being defined inside a function and therefore is hidden for other parts of code. Try "window.videoQArray" insted of "var ":
string createArrayScript = string.Format("window.videQarray = [{0}];", string.Join(",", videoQarray));
createArrayScript += string.Format("window.videQarrayList = [{0}];", string.Join(",", videoQarrayTitle));
Edit: It's a 2d array (ok, you wrote that very clearly in the question but I didn't see). Use JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
string createArrayScript = string.Format("window.videQarray = {0};", serializer.Serialize(videoQarray));
createArrayScript += string.Format("window.videQarrayList = {0};", serializer.Serialize(videoQarrayTitle));
Use The following function:
public static string ArrayToString2D(string[,] arr)
{
StringBuilder str = new StringBuilder();
str.Append("[['");
for (int k = 0; k < arr.GetLength(0); k++)
{
for (int l = 0; l < arr.GetLength(1); l++)
{
if (arr[k, l] == null)
str.Append("','");
else
str.Append(arr[k, l].ToString() + "','");
}
str.Remove(str.Length - 2, 2);
str.Append("],['");
}
str.Remove(str.Length - 4, 4);
str.Append("]]");
return str.ToString();
}
in the code behind have the following properties:
private string[,] upperLabels ;
public string UpperLabel
{
get
{ return Utils.ArrayToString2D(upperLabels); }
}
in the javascript use the following :
var upperSplitted = <%=UpperLabel%> ;
var value = upperSplitted[0][0];

Categories

Resources