Jagged arrays, populating them from a List<string> - c#

User enters a series of values into textboxes:
Textbox 1: 10,9,8,7
Textbox 2: 1,2,3,4
Id then like to sort these two string and populate a List<string>. Once sorted (already figured out how to do that part), id like to create a jagged array of the inputs like so:
string[][] Arr = new string[2][];
Arr[0] = new string[] { "10", "9", "8", "7" };
Arr[1] = .....
but instead of manually typing in the values, id like to use the List<string> mentioned above.
Is this possible (thus far, my attempts have failed rather miserably)? If not, could someone suggest a possible alternative approach?
Thanks for your time!
EDIT: Based on the answers, I got it working. Sorry again for not making it clear what I meant by sort.
List<string> tempString = new List<string>();
tempString.Add("10,9,8,7");
tempString.Add("1,2,3");
string[][] Arr = new string[2][];
for (int x = 0; x < 2; x++)
{
string[] values = tempString[x].Split(',').ToArray();
Arr[x] = values;
}

Create lists from the strings:
List<string> list1 = new List<string>(textbox1.Text.Split(','));
List<string> list2 = new List<string>(textbox2.Text.Split(','));
Sort the lists:
list1.Sort();
list2.Sort();
Now you can easily create arrays from the lists:
string[][] Arr = new string[2][];
Arr[0] = list1.ToArray();
Arr[1] = list2.ToArray();
If you want to do it in the other order, i.e. first sort then split, it would be:
List<string> list = new List<string>();
list.Add(textbox1.Text);
list.Add(textbox2.Text);
list.Sort();
string[][] Arr = new string[2][];
Arr[0] = list[0].split(',');
Arr[1] = list[1].split(',');

Arr[0] = textBox1.Text.Split(',');
Arr[1] = textBox2.Text.Split(',');
EDIT If you need preprocessing of the lists, you can just do it like so:
var array1 = textbox1.Text.Split(',').OrderBy(x => x).ToArray();
var array2 = textbox2.Text.Split(',').OrderBy(x => x).ToArray();
// extra processing here
string[][] Arr = new string[2][];
Arr[0] = array1;
Arr[1] = array2;

string[][] Arr = new string[]{textBox1.Text, textBox2.Text} //<--or "tempString"
.Select(s => s.Split(','))
.ToArray();

Related

Remove an element from an index array c#

if from an array like this one
string[] arr={"a", "b"};
Can i modify it in this way?
arr={"a"};
You can do it in the following different ways:
1)
var idx = 1;
arr = arr.Where((s, i) => i != idx).ToArray();
arr = arr.Where(s => s != "b").ToArray();
var filter = {"b"};
arr = arr.Except(​filter);
try this
arr = new string[] { arr[0] };

Splitting a string into 3 different arrays

I am receiving a string reply from serial port and this reply contains 3 different value. Every value is separated with ';'.
For example;
10;155.4587;0.01
I need to separate these values and add to a Listview box.
I've found examples of Split(';') function but i think it is not possible to assign split values to different arrays.
Is there any way to perform this extraction with using/not using split() function?
Thanks in advance for any help.
Assuming an array of input strings...
string[] a1 = new string[] {
"10; 155.4587; 0.01",
"20; 255.4587; 0.02",
"30; 355.4587; 0.03",
};
List<string> r1 = new List<string>();
List<string> r2 = new List<string>();
List<string> r3 = new List<string>();
foreach (string t1 in a1)
{
string[] t2 = t1.Split(";");
r1.Add(t2[0]);
r2.Add(t2[1]);
r3.Add(t2[2]);
}
There's a wide variety of methods to doing this, you could use a Regex to delimit each item and use Lambda functions.
You could do something more basic like manipulating the below drawn-out example:
string s = "10;155.4587;0.01";
string[] a = new String[1];
string[] b = new String[1];
string[] c = new String[1];
string[] z = s.Split(';');
for(int i=0; i< z.Length; i++)
{
switch(i)
{
case 0:
a[0] = z[i];
break;
case 1:
b[0] = z[i];
break;
case 2:
c[0] = z[i];
break;
}
}
Console.WriteLine(a[0] + ' ' + b[0] + ' ' + c[0]);
The above illustrates how to manipulate elements but doesn't scale exactly well you may wish to pursue the anonymous route with the first comment using lambdas (see mukesh kudi's answer).
You can get this with help of linq...
string s = "10;155.4587;0.01";
var arrList = s.Split(';').Select(x => new string[] { x }).ToArray();
Here arrList contains three arrays. but i am not sure how this will help you. if you want to bind this result with ListView you have to traverse this collection and get each array value and bind to listview. you can do this with single array by traverse it's index's.
EDIT
To add just one list view item use:
var s = "10;155.4587;0.01";
var values = s.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
var listViewItem = new ListViewItem(values[0]);
listViewItem.SubItems.Add(values[1]);
listViewItem.SubItems.Add(values[2]);
listView1.Items.Add(listViewItem);
Assuming you have multiple strings to populate the listBox, try:
ListView listView1 = new ListView();
listView1.Bounds = new Rectangle(new Point(10, 10), new Size(300, 200));
listView1.View = View.Details;
listView1.GridLines = true;
listView1.Columns.Add("TD");
listView1.Columns.Add("AD");
listView1.Columns.Add("CT", -2);
var sValues = new string[] { "10;155.4587;0.01", "11;156.4587;0.02", "12;157.4587;0.03" };
var values = sValues.Select(x => x.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
.Select(x =>
{
var listViewItem = new ListViewItem(x[0]);
listViewItem.SubItems.Add(x[1]);
listViewItem.SubItems.Add(x[2]);
return listViewItem;
});
listView1.Items.AddRange(values.ToArray());
Thanks for all the help.
With the suggestion of #Captain Wibble, i successfully decoded my replies and add to Listview item.
Here is what i did for anyone in same trouble;
First i added my data packages "\r\n"
10;12.2345;0.01\r\n
I used;
serial.ReadLine()
Function to receive incoming data.
To decode and store the data into a listview object i use;
var s = text;
string[] a = new String[3];
//string[] b = new String[1];
//string[] c = new String[1];
string[] z = s.Split(';');
for (int i = 0; i < z.Length; i++)
{
switch (i)
{
case 0:
a[0] = z[i];
break;
case 1:
a[1] = z[i];
break;
case 2:
a[2] = z[i];
break;
}
}
itm = new ListViewItem(a);
listView5.Items.Add(itm);

How do I add a string array within a string array array in a string list?

I have a string[,] with a set amount of string[] that stay the same and want to pick a few of them and put them in a list<string[]> (I use a list to make it ever extendable). But the list<string[]> won't accept any string[] from the string[,].
string[,] testArray =
{
{"testValue1", "testValue1.1"}
{"testValue2", "testValue2.1"}
{"testValue3", "testValue3.1"}
}
List<string[]> testList = new List<string[]>();
testList.Add(testArray[1]) //error: wrong number of indicaters inside[]
testList.Add(testArray[1,1]) //error: cannot convert from string to string[]
What you have there is a 2D array, not a jagged array (array of arrays).
You can't directly reference the entire row of a 2D array (unlike a jagged array).
The easy solution is to use a jagged array string[][] but if you expressly don't want to do that you can achieve the same thing by looping over the row of the 2D array yourself and buffering it into another array
string[,] testArray =
{
{"testValue1", "testValue1.1"},
{"testValue2", "testValue2.1"},
{"testValue3", "testValue3.1"}
};
List<string[]> testList = new List<string[]>();
string[] arrayRow = new string[testArray.GetLength(1)]; // zero index dimension to get length of
int i = 0; // row to copy
for (int j = 0; j < testArray.GetLength(1); j++) { // loop over row
arrayRow[j] = testArray[i, j];
}
testList.Add(arrayRow); // {"testValue1", "testValue1.1"} added to list
Either you can use jagged array or for loop for 2d array:
Jagged array:
new string[] {"testValue1", "testValue1.1"},
new string[] {"testValue2", "testValue2.1"},
new string[] {"testValue3", "testValue3.1"}
};
List<string[]> testList = new List<string[]>();
testList.Add(testArray[1]); //second row of jagged array
2d array:
string[,] testArray =
{
{"testValue1", "testValue1.1"},
{"testValue2", "testValue2.1"},
{"testValue3", "testValue3.1"}
};
List<string[]> testList = new List<string[]>();
string[] secnd_rw=new string[testArray.GetLength(1)] ;
for (int i = 0; i < testArray.GetLength(1); i++)
{
secnd_rw[i] = testArray[1,i];
}
testList.Add(secnd_rw); //second row of 2d array
I have a string[,] with a set amount of string[]
This is actually not true because you are using the multidimensional array instead of the jagged array. If you are using the [,] you could not out of the box take the whole row as if you are using [][].
Jagged
string[][] testArray =
{
new [] {"testValue1", "testValue1.1"},
new [] {"testValue2", "testValue2.1"},
new [] {"testValue3", "testValue3.1"}
};
Console.WriteLine(string.Join(", ", testArray[0])); //testValue1, testValue1.1
2D Array
string[,] testArray =
{
{"testValue1", "testValue1.1"},
{"testValue2", "testValue2.1"},
{"testValue3", "testValue3.1"}
};
Console.WriteLine(string.Join(", ", testArray.GetColumn(0))); //testValue1, testValue1.1
public static class ArrayExt
{
public static IEnumerable<string> GetColumn(this string[,] array, int column)
{
return Enumerable.Repeat(column, array.GetLength(1))
.Zip(Enumerable.Range(0, array.GetLength(1)), (x,y) => new { X = x, Y = y })
.Select(i => array[i.X, i.Y]);
}
}

groupping/sorting/splitting 2D list/array

I have following 2D array
var array1 = new string[][]
{
new string[] {A,B,C},
new string[] {A,X,Y},
new string[] {D,L,K},
new string[] {A,X,W}
};
At the end I would like to sort or group this list and output I want to display on my MVC view on a table as below
A / X / Y,W
/ B/ C
D/ l / K
I dont want to show repeated elements in the column. So it means like groupping.
How can I group the results in controller with linq.
Sorting might also help if I can sort by first element and then 2nd etc.
Another idea also works that if I can split into 3 1D arrays? So at the end i would have array1 ={A,A,D,A}, array2={B,X,L,X}, array3= {C,Y,K,W}
Thanks.
You could do something like:
var array1 = new string[][]
{
new string[] {"A","B","C"},
new string[] {"A","X","Y"},
new string[] {"D","L","K"},
new string[] {"A","X","W"},
};
var s = array1.Select(a => string.Concat(a)).ToList();
s.Sort();
// Now you have them sorted as a list of strings, do what you want...
this will not limit you to 3 entries (didn't like the hardcoded [0],[1] etc...)
Your problem should be split into two subproblems. First, you need to sort the array1; second, you need out array1 using the fact the array1 is sorted.
You can't use grouping instead of sorting, cause a grouping is not guarantee that subarrays with the same first element will follow each other.
var array1 = new List<IList<string>>
{
new List<string> {"A", "X", "Y"},
new List<string> {"A", "X", "W"},
new List<string> {"A", "B", "C"},
new List<string> {"D", "L", "K"},
};
var array2 = from a in array1
orderby a[0], a[1], a[2]
select a;
var array3 = array2.ToList();
Now you can use array2 in Razor:
#if (array2.MoveNext())
{
#array2.Current[0], #array2.Current[1], #array2.Current[3]<br />
var lastElement = array2.Current;
while (array2.MoveNext())
{
if (array2.Current[0] != lastElement[0])
{
#array2.Current[0],
}
else if (array2.Current[1] != lastElement[0])
{
#array2.Current[1],
}
#array2.Current[2]
lastElement = array2.Current;
}
}

Convert jagged array of string to list of list of string in C#

I want to convert string[][] to List<List<string>>.
eg.
List<List<string>> listOfListReturned = new List<List<string>>();
string[][] twoDArrOfString = new string[2][];
I want to convert twoDArrOfString to listOfListReturned
Please suggest, how to do it?
Regards,
Vivek
Something like the following will also work:
string[][] twoDArrOfString = new string[2][];
var res = twoDArrOfString
.Where(inner => inner != null) // Cope with uninitialised inner arrays.
.Select(inner => inner.ToList()) // Project each inner array to a List<string>
.ToList(); // Materialise the IEnumerable<List<string>> to List<List<string>>
You need to handle nulls if the inner arrays have not been initialised.
If you aren't going to enumerate through all of these, you might want to drop the final ToList and simply work against the IEnumerable<List<string>> to avoid resolving all inner lists if you don't need to (taking advantage of the deferred execution of enumerables).
Any reason in particular why you are doing this?
List<List<string>> listOfListReturned = new List<List<string>>();
string[][] twoDArrOfString = new string[2][];
twoDArrOfString[0] = new[] {"a", "b"};
twoDArrOfString[1] = new[] {"c", "d"};
foreach (var s in twoDArrOfString)
{
listOfListReturned.Add(new List<string>(s));
}
Or
var result = twoDArrOfString.ToList();
var listOfList = result.Select(x => x.ToList()).ToList();
Not tested just imagine it :)
for (int i = 0; i < twoDArrOfString.Length; i++)
{
for (int j = 0; j < twoDArrOfString[i].Length; j++)
{
listOfListReturned[i].Add(twoDArrOfString[j].ToString());
}
listOfListReturned.Add(listOfListReturned[i]);
}
A more linq-ish version might be
List<List<string>> listOfListReturned = new List<List<string>>()
{
new List<string> {"A", "B"},
new List<string> {"C", "D"},
};
string[][] twoDArrOfString = new string[2][]
{
new [] {"A", "B"},
new []{"C", "D"},
};
var actual = twoDArrOfString.Select(arr => new List<string>(arr)).ToList();
for (var idx = 0; idx < listOfListReturned.Count; idx++) {
CollectionAssert.AreEqual(listOfListReturned[idx], actual[idx]);
}
EDIT: Adam's solution above allowing for empty rows is better.

Categories

Resources