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];
Related
I need to create dynamic references to both strings and string Arrays within a for loop.
Is the following correct? In particular where I am trying to create a dynamic string reference string sRef = "svert"+num; and later a dynamic Array reference string arrayRef = "s_array"+num;
Any feedback welcome.
Vector3[] meshVerts = foo;
for(int num=0; num < meshVerts.Length;num++){
string sRef = "svert"+num;
sRef =meshVerts[num].ToString( format: "F4");
sRef= sRef.Substring(1, 3);
string arrayRef = "s_array"+num;
string[] arrayRef = sRef.Split(',');
}
'''
I have prepared a sample and test code for your question. I hope you find it interesting.
//fill vector3 array
Vector3[] meshVerts = new Vector3[3];
for (int i = 0; i < meshVerts.Length; i++)
{
meshVerts[i] = new Vector3(i, i + 1, i + 2);
}
//fill string array
string[] arrayRef = new string[meshVerts.Length];
for (int num = 0; num < meshVerts.Length; num++)
{
arrayRef[num] = string.Format("s_array{0}: {1}", num, meshVerts[num]);
}
//show vector3 array and string array
for (int i = 0; i < meshVerts.Length; i++)
{
Console.WriteLine(string.Format("Vector3 Array Row{0}: X={1} ,Y={2} ,Z={3}", i, meshVerts[i].X, meshVerts[i].Y, meshVerts[i].Z));
string[] newArray = arrayRef[i].Split(',');
string firstCell = newArray[0].Split(':')[1].Replace("<", "");
Console.WriteLine(string.Format("{0} Row{1}: X={2} ,Y={3} ,Z={4}", newArray[0].Split(':')[0], i, firstCell, newArray[1], newArray[2].Replace(">", "")));
}
Basically, I am trying to split an array and want to pass its value into another array.
But, I am not able to do it.It is givin an error:
Cannot implicitly convert type String[] to string"
StreamReader EmployeeFile = new StreamReader(#"C:\Users\user\Desktop\FoodDeliverySystem\Employee_details.txt");
String ReadEmployeeData = EmployeeFile.ReadToEnd();
String[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for (int k = 0; k < 5; k++)
{
for (int l = 0; l < 5; l++)
{
Console.WriteLine("test");
String[,] ReadEmployeeDataByLineByCategorie = new string[k, l];
ReadEmployeeDataByLineByCategorie[k,l] = ReadEmployeeDataByLine[l].Split(',');
}
}
Since you can't be sure of how many of those values you're gonna have in each category of yours, you should use jagged arrays
That should do:
var readEmployeeDataByLine = new StreamReader(#"C:\pathToFile.txt").ReadToEnd().Split(';');
var readEmployeeDataByLineByCategorie = new string[readEmployeeDataByLine.Length][];
for (int i = 0; i < readEmployeeDataByLineByCategorie.Length; i++)
readEmployeeDataByLineByCategorie[i] = readEmployeeDataByLine[i].Split(',');
ReadEmployeeDataByLineByCategorie[k,l] is a string
while ReadEmployeeDataByLine[l].Split(',') is a string[]
string[] ReadEmployeeDataByLine = ReadEmployeeData.Split(';');
for(int i = 0;i< ReadEmployeeDataByLine.Length;i++)
{
string split = ReadEmployeeDataByLine[l].Split(',');
for(int j=0; j<split.Length;j++)
ReadEmployeeDataByLineByCategorie[i,j] = split[j]
}
I'm making a webshop for school and had a quick question.
I'm trying to write a code that generates a random coupon code and it actually works (did some extreme programming in Console Application), but it's simply not efficient.
static void Main(string[] args)
{
Random r = new Random();
string ALphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 4;
char[] code1 = new char[size]
char[] code2 = new char[size]
char[] code3 = new char[size]
for (int i = 0; i < size; i++)
{
code1[i] = Alphabet[r.Next(Alphabet.Length)];
code2[i] = Alphabet[r.Next(Alphabet.Length)];
code3[i] = Alphabet[r.Next(Alphabet.Length)];
}
string code4 = new string(code1);
string code5 = new string(code2);
string code6 = new string(code3);
Console.WriteLine(code4 + " - " + code5 + " - " + code6);
Console.ReadLine();
}
This works.. somehow. But I would like to see it more efficient, because when I want to generate 100 coupons... this isn't really the way to do that.
I did see something on joining strings, use string.Insert to get that " - " in between and loop it multiple times, but I couldn't get a clear tutorial on how to do that with... well this kind of code.
Anyone got a efficient and (preferable) easy solution?
=======
UPDATE!
this does end up in a database eventually
You could be using a StringBuilder for this:
StringBuilder sb = new StringBuilder();
Random r = new Random();
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 16;
for (var i = 0; i < size; i++)
{
sb.Append(Alphabet[r.Next(Alphabet.Length)]);
}
Console.WriteLine(sb.ToString());
If you want less code you can make use of a GUID and format it.
Guid.NewGuid().ToString("N").Substring(0, 16);
Update, just saw you needed some formatting between each part of the coupon, so I changed it a litle bit:
StringBuilder sb = new StringBuilder();
Random r = new Random();
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int pieces = 3, pieceSize = 4;
for (var i = 0; i < pieces; i++)
{
if(i != 0)
sb.Append(" - ");
for (var j = 0; j < pieceSize; j++)
{
sb.Append(Alphabet[r.Next(Alphabet.Length)]);
}
}
Console.WriteLine(sb.ToString());
Code is not quite good, but for school app will play I guess )
static string GenerateCoupon(Random r)
{
string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int size = 4;
char[] code1 = new char[size];
char[] code2 = new char[size];
char[] code3 = new char[size];
for (int i = 0; i < size; i++)
{
code1[i] = Alphabet[r.Next(Alphabet.Length)];
code2[i] = Alphabet[r.Next(Alphabet.Length)];
code3[i] = Alphabet[r.Next(Alphabet.Length)];
}
string code4 = new string(code1);
string code5 = new string(code2);
string code6 = new string(code3);
return string.Format("{0}-{1}-{2}", code4, code5, code6);
}
static void Main(string[] args)
{
Random rnd = new Random();
for (int i = 0; i < 100;i++ )
Console.WriteLine(GenerateCoupon(rnd));
Console.ReadLine();
}
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++;
}
}
Let's say you have the string "This is a test"
I pass it to method zee, like ("This is a test", 1)
and want "test This is a";
I pass it to method zee, like ("This is a test", 2)
and want "a test This is";
the number can exceed the total words in variable. If it does it should loop around.
I started with....
public static string zee(string origString, int i)
{
StringBuilder sb = new StringBuilder();
ArrayList list = new ArrayList();
list.AddRange(origString.Split(' '));
// not sure here -
for (int c = i; c < (list.Count + i); c++)
{
sb.AppendFormat("{0} ", list[c]);
}
return sb.ToString();
}
for(int j=0; j < list.length; j++){
int idx = (j + i) % list.length;
sb.AppendFormat("{0} " , list[idx]);
}
Mostly like Brent Arias's solution, but I think a for loop is more readable, less likely to go infinite.
public static string zee(string origString, int i)
{
StringBuilder sb = new StringBuilder();
List<string> list = new List<string>();
list.AddRange(origString.Split(' '));
for (int j = 0; j < list.Count; j++)
{
int idx = (j + i) % list.Count;
sb.AppendFormat("{0} ", list[idx]);
}
return sb.ToString();
}
This is how I'd solve it.
private static string f(string s, int start)
{
var arr=s.Split(' ');
start %= arr.Length;
var res=arr.Skip(arr.Length - start).ToList();
res.AddRange(arr.Take(arr.Length - start));
return string.Join(" ", res);
}
I tried writing a one liner with linq but I don't see how to combine 2 lists. Union and Join aren't what I need.
This is how I'd solve it using strings.
public static string zee(string origString, int i)
{
string[] splitStr = origString.Split(' ');
string newStr = "";
// Not sure what you meant by wrap around but this should
// do the trick.
i %= splitStr.Length;
for (int j = (splitStr.Length - i); j < splitStr.Length; j++)
newStr += splitStr[j] + " "; // Add spaces taken by split :(
for (int j = 0; j < (splitStr.Length - i); j++)
newStr += splitStr[j] + " ";
return
newStr;
}
Here's an abomination trying to cram as much into one line as possible:
static string zee(string sentence, int wordCount)
{
var words = sentence.Split(' ');
return string.Join(" ", new[] { words.Skip(words.Count() - wordCount), words.Take(words.Count() - wordCount) }.SelectMany(w => w).ToArray());
}
I havn't tried it, but I think this would do it:
i %= list.Length;
int index = i;
do {
index %= list.Length;
sb.AppendFormat("{0} ", list[index]);
while (++index != i);
static string rearrange(string phase,int index)
{
string[] words = phase.Split(' ');
string[] newwords = new string[words.Length];
int pointer = index;
for (int i = 0; i < words.Length;i++ )
{
if(pointer>=words.Length)
{
pointer = 0;
}
newwords[i] = words[pointer];
pointer++;
}
return string.Join(" ", newwords);
}
Sounds like a homework question to me, but here is an efficient use of the .Net framework:
private static string [] SplitWords(string s, int startWord)
{
string[] words = s.Split(' ');
List<string> output = new List<string>();
output.AddRange(words.Skip(startWord).ToArray());
output.AddRange(words.Take(startWord).ToArray());
return output.ToArray();
}
There is absolutely no error checking in this function so you will have to modify it for production code but you get the idea.
public string SetStart(int startAt)
{
const string sentence = "this is a test so it is";
var words = sentence.Split(' ');
var x = (startAt > words.Count()) ? startAt%words.Count() : startAt;
return string.Join(" ", words.Skip(x).Concat(words.Take(x)));
}