add values in string array on runtime c# - c#

i am getting string array on runtime like this
string[] array1 = {"5", "4", "2"};
values in array is added on runtime on the basis of checkbox selection from
screen (Note: i have 7 check boxes on screen )
if i check 3 check boxes then 3 values will be add in array1 but i want to add
zero at the end of the array in remaining 4 positions in array like this :
string[] array1 = {"5", "4", "2","0" ,"0","0" , "0"};
during runtime just to fix all 7 position in array ...what should i do ??

I don't get the usage of your requirement. But you can fill up the array with "0" with the following code:
List<string> list = array1.ToList();
for (int i = array1.Length; i < 7; i++)
{
list.Add("0");
}
array1 = list.ToArray();

You can do the following:
const int paddedSize = 7;
var newArray = array1.Concat(Enumerable.Repeat("0", paddedSize - array1.Length)).ToArray();
But maybe you'll understand it better without using Linq; the type you want to use is List<string> which can be dynamically resized, arrays can't. In order to get a list out of an array, you can use the linq extension:
var resized = array1.ToList();
Or
var resized = new List<string>(array1);
And now you simply add 0s until the total count of items is 7:
while (resized.Count < paddedSize)
resized.Add("0");
And back to an array:
var newArray = resized.ToArray();

Related

Sort two dimensional array with different lengths

Hi fellow programmers,
I am trying to sort a two dimensional array. This array represent a collection of objects which has a property which have a value in the list underneath. So the original list does not have to be saved.
The starting situation is:
var list = new List<string>
{
"10-158-6",
"11-158-6",
"90-158-6",
"20-15438-6",
"10-158-6",
"10-158-6-3434",
"10-1528-6"
};
The result should be
var list = new List<string>
{
"10-158-6",
"10-158-6",
"10-1528-6"
"10-158-6-3434",
"11-158-6",
"20-15438-6",
"90-158-6",
};
It should be first ordered on the first part -> then the second -> etc. etc.
I think it is almost impossible to sort these strings so I converted it to a two-dimensional list. I found different solutions to sort multi dimensional list but none can be used for this problem. Also I do not have a clue where to start...
Anyone has an idea how to write a sorting algorithm that doesn't have unnecessary huge big O?
Thanks in advance!
Jeroen
You can use Sort method; let's implement a general case with arbitrary long numbers:
Code:
var list = new List<string>() {
"10-158-6",
"11-158-6",
"90-158-6",
"20-15438-6",
"10-158-6",
"10-158-6-3434",
"10-1528-6",
"123456789012345678901234567890"
};
list.Sort((left, right) => {
var x = left.Split('-');
var y = right.Split('-');
// Compare numbers:
for (int i = 0; i < Math.Min(x.Length, y.Length); ++i) {
// Longer number is always bigger: "123" > "99"
int r = x[i].Length.CompareTo(y[i].Length);
// If numbers are of the same length, compare lexicographically: "459" < "460"
if (r == 0)
r = string.CompareOrdinal(x[i], y[i]);
if (r != 0)
return r;
}
// finally, the more items the bigger: "123-456-789" > "123-456"
return x.Length.CompareTo(y.Length);
});
// Let's have a look at the list after the sorting
Console.Write(string.Join(Environment.NewLine, list));
Outcome:
10-158-6
10-158-6
10-158-6-3434 // <- please, note that since 158 < 1528
10-1528-6 // <- "10-158-6-3434" is before "10-1528-6"
11-158-6
20-15438-6
90-158-6
123456789012345678901234567890
Those look like Version number. If a change from Dash to Dot are not a big change you can simply use C# Version
var list = new List<string>
{
"10-158-6",
"11-158-6",
"90-158-6",
"20-15438-6",
"10-158-6",
"10-158-6-3434",
"10-1528-6"
};
var versions = list.Select(x => new Version(x.Replace('-','.'))).ToList();
versions.Sort();
LiveDemo

Add two list data into array while using if condition

I have two lists, one list have some record (not known specific no of rec, but not more than 13 records) and second list have only empty value. I am using if condition on these two list. And want to add these two list in one array. I am using this code:
for (int i=0; i>12; i++)
{
List<string> excList = new List<string>();
//added column from table, which can varies
excList.Add((string)column.ColumnName);
string[] excelList = new string[] { };
List<string> stack = Enumerable.Range(excList.Count, 13)
.Select(z => string.Empty)
.ToList<string>();
if (excList.Count > i)
{
excelList = excList.ToArray();
}
if (excList.Count <= i)
{
excelList = stack.ToArray();
}
eCol0 = excelList[0].ToString();
//show first value, after adding two list in excelList
response.Write(eCol0);
}
Using this code, when the second condition started and list (excList) is adding in array (excelList) then excelList is showing only second list data.
I want to insert these two list (excList and stack) into arrayList (which have range of 13).But these two list must add on the bases of if condition as I'm using if condition in above code.
Well you never Add something to your string array excelList. You always assign it new.
Using an array is also not the best for adding values, since you need to know beforehand the size of the array.
If you really want an array in the end with both results, you should do something like this:
List<string> excList = new List<string>();
... fill your excList here and initialize the stack list with whatever you need ...
excList.AddRange(stack);
string[] excelList = excList.ToArray();
Edit: as the comments mention, your question is a little bit confusing and you are using one big loop with no clear reason why and adding empty values makes no sence too... so i tried to get the essence out of what you wanted to know
Edit:2
Wait a second, I think you want in the end, an array of strings, with the size of 13, where the elements are at least string.empty
List<string> excList = new List<string>();
//added column from table, which can varies
excList.Add((string)column.ColumnName);
string[] excelList = new string[13];
for (int i = 0; i < excList.Count; i++)
{
excelList[i] = excList[i];
}
for (int i = excList.Count; i < 13; i++)
{
excelList[i] = string.Empty;
}
no outer loop necessary
You've written a huge amount of confusing code that could be considerably more compact.
Through th commnts I was able to understand that you have a list of N strings, where N could be between 1 and 13, and you want to turn it into an array of 13 strings with all your list items at the start, and empty strings at the end
So a list of:
"a", "b", "c"
Becomes an array of:
"a", "b", "c", "", "", "", "", "", "", "", "", "", ""
If you want a one liner to generate you a list of 13 strings, from a List x of up to 13 strings:
string[] arrayOf13 = x.AddRange(Enumerable.Repeat("", 13 - x.Count)).ToArray();
If your list x will have an unknown number more than 13:
string[] arrayOf13 = x.AddRange(Enumerable.Repeat("", 13)).Take(13).ToArray();
Or without LINQ using either a for or a while loop:
for(; x.Count < 13; x.Add(""))
string[] arrayOf13 = x.ToArray();
while(x.Count < 13)
x.Add(""));
string[] arrayOf13 = x.ToArray();
If you're willing to have the strings be null rather than empty, you can just declare an array of size 13 (all null) and then use Array.CopyTo():
string[] arrayOf13 = new string[13];
x.ToArray().CopyTo(arrayOf13, 0);
It seems your goal is to get an array of 13 strings (excelList), where each element is eigher string.Empty by default or the corresponding (same index) element from some source list (excList).
So a short-code solution would be to first create a 13-element array, initialized with 'string.Empty' and then copy the source lists elements over, limited to max 13 elements:
var excelList = Enumerable.Repeat(string.Empty, 13).ToArray();
excList.CopyTo(0, excelList, 0, Math.Min(13, excList.Count));

How to rearrange the columns in an array in C#?

So I have an array with 4 columns. And I also have a separate list which defines each column with a string. Something like the snippet below:-
List<string> headers = new List<string>();
headers.Add("Name");
headers.Add("Number");
headers.Add("ID");
headers.Add("License");
The array looks like this
Max 32445 1 KPFG35
Bill 33234 2 DGWEF9
Ruth 89428 3 SFD3FG
... and so on.
Now, lets say someone wants that same array however with the columns arranged as ID, Name, Number, License. How can I manipulate the columns in the array and produce a new one to return? thank you for any help!
so in the case mentioned above, it would return
1 Max 32445 KPFG35
2 Bill 33234 DGWEF9
3 Ruth 89428 SFD3FG
I don't know if you have to use List or not. But here is a solution that may help you. I suggest you to use DataTable.
Basically I have create a form with datagridview and a button,
DataTable dt = new DataTable();
In form's load,
private void Form1_Load(object sender, EventArgs e)
{
dt.Columns.Add("Name");
dt.Columns.Add("Number");
dt.Columns.Add("ID");
dt.Columns.Add("License");
string[] array = { "Max", "32445", "1", "KPFG35", "Bill", "33234", "2", "DGWEF9", "Ruth", "89428", "3", "SFD3FG" };
for (int i = 0; i < array.Length + 1; i++)
{
if (i != 0 && i % 4 == 0) // every 4th item should be split from list
{
string[] tempArray = new string[4]; //temp array will keep every item until 4th one.
tempArray = array.Take(i).ToArray(); //Take until 4th item.
array = array.Skip(i).ToArray(); //then we don't need that items so we can skip them
dt.Rows.Add(tempArray); //Row is done.
i = -1; //Every skip will generate a new array so it should go back to 0.
}
}
dataGridView1.DataSource = dt;
}
And there is a button to change order with SetOrdinal,
private void button1_Click(object sender, EventArgs e)
{
dt.Columns["ID"].SetOrdinal(0);
dataGridView1.DataSource = null;
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
}
Output,
After button click ID column was at 0. (the second one)
Hope helps, (Not sure if you have to use List<string>, but it might be a clue for you.
You are not actually shifting the columns but are rearranging them. Shifting means the columns remain in the same order but the row is rotated left or right. Anyway, doing it without using data structures but just using arrays would take the following form in code:
//Assuming the array is of type string
string[,] arr <--- the array we are talking about
string[,] ta = new string[3,4]; //a temporary array
/* The columns are arranged in the order: Name Number ID License
and we want it as: ------------ ID Name Number License
So, if the order of the columns is: 1 2 3 4,
we now want it as: -------------- 3 1 2 4 */
string order = "3124";
for(int i=0; i<3; i++){
for(int j=0; j<4; j++){
int k = int.Parse(order[j].ToString())-1;
//k stores the column number in arr to be added to ta
ta[i,j] = arr[i,k];
}
}
//ta now stores arr in the new order
//you can either change the value of arr to the new array: arr = ta;
//or you can now make all your references to the new array ta
Hope it helps you.
As others have suggested: It would probably be better for you to store these as objects for maintainability.
But It sounds like you have a requirement that the array is what you want to keep. Since all you really want to do is move a column over you and produce a new list you could do something like:
private static IEnumerable<string> MoveIndexToFirst(List<string> input)
{
for(int i = 0; i < input.Count; i+=4 )
{
yield return input[i+2];
yield return input[i];
yield return input[i+1];
yield return input[i+3];
}
}
usage:
List<string> newList = MoveIndexToFirst(yourData).ToList();

Unable to find intersection of two array

I have one array int[] com which contains two values 0 and 1 (at initial stage).
I define one more array as String[] arr = new String[100];
arr contains 6 elements which are:
arr[0]={4,8,10,11,12,14}
arr[1]={1,2,3,4,8,12,14}
.. arr[6]=something
I want to find intersection of arr[0] and arr[1], so I wrote the code as:
foreach (int value1 in intersect)
{
//perform logic
}
Here I should get value1 as 4,8 but i am getting value1 as 52,44.
What is wrong with what I am doing?
Ok here is what you are doing, you have string arrays not int arrays. If you do this
arr[0]="4,8,10,11,12,14";
arr[1]="1,2,3,4,8,12,14";
var intersection = arr[0].Intersect(arr[1]);
since arr[0] and arr[1] are strings, you'll get as the result this list of chars '4', ',' , '8', '1', '2' which corresponds respectively to the integer values 52 44 56 49 50 which is exactly what you are getting.
You should declare integer matrix instead of array of strings int [,] arr = new int[100,100]; or even better List<List<int>>. You can't use integers like strings, at least not in this context.
List<List<int>> arr = new List<List<int>>();
arr.Add(new List<int>{4,8,10,11,12,14});
arr.Add(new List<int>{1,2,3,4,8,12,14});
var intersection = arr[0].Intersect(arr[1]);
But if you don't believe me, and want to be sure that your previous code doesn't make sense, change the foreach loop and see what's happening:
foreach (char value1 in intersect)
{
//perform logic
}
In addition, you don't need to do this:
int zero= Convert.ToInt32(com[0].ToString());
int one= Convert.ToInt32(com[1].ToString());
You could replace it with something like:
int zero= com[0];
int one = com[1];
but nevertheless it's pointless since you can do this:
arr[com[0]]
arr[com[1]]
The LINQ Intersect method correctly computes the intersection between arrays:
var a = new [] {4,8,10,11,12,14};
var b = new [] {1,2,3,4,8,12,14};
var intersection = a.Intersect(b);
// intersection:
// IEnumerable<int> { 4, 8, 12, 14 }
The above code - which represents a minimum non-failing counter example - was run in LINQPad.
Note that Intersect relies on Equals, so it's possible to "break" it:
var a = new object[] {4,8,10,11,12,14};
var b = new object[] {"1","2","3","4","8","12","14"};
var intersection = a.Intersect(b);
// intersection:
// IEnumerable<object> { }
Of course, this doesn't account for "random new values" - that's just a bug elsewhere.

How to get the length of row/column of multidimensional array in C#?

How do I get the length of a row or column of a multidimensional array in C#?
for example:
int[,] matrix = new int[2,3];
matrix.rowLength = 2;
matrix.colLength = 3;
matrix.GetLength(0) -> Gets the first dimension size
matrix.GetLength(1) -> Gets the second dimension size
Have you looked at the properties of an Array?
Length gives you the length of the array (total number of cells).
GetLength(n) gives you the number of cells in the specified dimension (relative to 0). If you have a 3-dimensional array:
int[,,] multiDimensionalArray = new int[21,72,103] ;
then multiDimensionalArray.GetLength(n) will, for n = 0, 1 and 2, return 21, 72 and 103 respectively.
If you're constructing Jagged/sparse arrays, then the problem is somewhat more complicated. Jagged/sparse arrays are [usually] constructed as a nested collection of arrays within arrays. In which case you need to examine each element in turn. These are usually nested 1-dimensional arrays, but there is not reason you couldn't have, say, a 2d array containing 3d arrays containing 5d arrays.
In any case, with a jagged/sparse structure, you need to use the length properties on each cell.
for 2-d array use this code :
var array = new int[,]
{
{1,2,3,4,5,6,7,8,9,10 },
{11,12,13,14,15,16,17,18,19,20 }
};
var row = array.GetLength(0);
var col = array.GetLength(1);
output of code is :
row = 2
col = 10
for n-d array syntax is like above code:
var d1 = array.GetLength(0); // size of 1st dimension
var d2 = array.GetLength(1); // size of 2nd dimension
var d3 = array.GetLength(2); // size of 3rd dimension
.
.
.
var dn = array.GetLength(n-1); // size of n dimension
Best Regards!
Use matrix.GetLowerBound(0) and matrix.GetUpperBound(0).
You can also use:
matrix.GetUpperBound(0);//rows
matrix.GetUpperBound(1);//columns

Categories

Resources