Subarrays[][] from jagged Array[][] - c#

I have an array
string[][] where data will look like this:
p,x,y,w,t,p,f,c,n,n,e,e,s,s,w,w,p,w,o,p,k,s,u
e,x,s,g,f,n,f,w,b,k,t,e,s,s,w,w,p,w,o,e,n,a,g
e,x,y,y,t,a,f,c,b,n,e,c,s,s,w,w,p,w,o,p,k,n,g
e,b,s,w,t,a,f,c,b,g,e,c,s,s,w,w,p,w,o,p,k,n,m
e,b,y,w,t,l,f,c,b,n,e,c,s,s,w,w,p,w,o,p,n,s,m
p,x,y,w,t,p,f,c,n,p,e,e,s,s,w,w,p,w,o,p,k,v,g
.
.
.
colums are Attributes (eg. 1st col has 2 values (p,e)
I'm trying to create sub arrays based on attribute values eg.
subarray1
p,x,y,w,t,p,f,c,n,n,e,e,s,s,w,w,p,w,o,p,k,s,u
p,x,y,w,t,p,f,c,n,n,e,e,s,s,w,w,p,w,o,p,k,s,u
subarray2
e,x,s,g,f,n,f,w,b,k,t,e,s,s,w,w,p,w,o,e,n,a,g
e,x,y,y,t,a,f,c,b,n,e,c,s,s,w,w,p,w,o,p,k,n,g
e,b,s,w,t,a,f,c,b,g,e,c,s,s,w,w,p,w,o,p,k,n,m
e,b,y,w,t,l,f,c,b,n,e,c,s,s,w,w,p,w,o,p,n,s,m
.
.
i tryed with this:
public string[][] subSets2(string[][] _dataSet, int AttributeID, int value)
{
string[][] SS=new string[_dataSet.Length][];
List<string> values=Transpose(_dataSet)[AttributeID].Distinct().ToList();
int t= 0;
string[][] tempSS = Transpose(_dataSet);
for (int i= 0;i< _dataSet.Length;i++)
{
SS[t]= new string[_dataSet[i].Count()];
for (int j = 0; j<_dataSet[i].Count() ; j++)
{
if (_dataSet[i][j].Equals(values[value]) && AttributeID== j)
{
SS[t][j] = _dataSet[i][j];
t++;
}
}
}
return SS;
}

If you want to create sub arrays based on a given column you can use linq as follows:
var subarrays = _dataSet.GroupBy(r => r[0]).Select(r => r.ToArray()).ToArray();
The r[0] refers to the first item in each array. You can change the index to group by a different column.

I'm not sure I understand the question, but if I do, then you want to get a jagged array that contains all the arrays that starts with a specific string ("p" or "e").
If that is the case, you can simply use linq's where extension method:
public string[][] subSets(string[][] _dataSet, string valueOfFirstCell)
{
return _dataSet.Where(d => d[0] == valueOfFirstCell).ToArray();
}

Related

C# Array in array

I'm stuck trying to create array of arrays..
This is what i have for now, i would appreciate if someone could point me to right direction.
I have .txt file which has paths to images and each string has desired output separated with "|" like so:
":\\\img.png|1"
I'm trying to create array that has 2 columns and number of imagepaths as rows. Col 0 being a array of flattened rgb values of the image and col 1 being output as int.
I'm getting error from line Data[i][0] = Flat;
"Cannot implicitly convert type 'int[]' to 'int'"
It might be obvious to more experienced coders here but i cant wrap my head around this.
static int[][] CreateDataSet(string DatasetPath)
{
string[] Lines = File.ReadAllLines(DatasetPath);
int[][] Data = new int[Lines.GetUpperBound(0)][];
for (int i = 0; i <= Lines.GetUpperBound(0); i++)
{
Data[i] = new int[2];
string[] StringSplit = Lines[i].Split('|');
Data[i][1] = Convert.ToInt32(StringSplit[1]);
int[] Flat = FlattenArray(ImagetoArray(StringSplit[0]));
Data[i][0] = Flat;
}
return Data;
}
In an array, all elements must have same type (or at least must be assignable to a variable of the element's type).
You have two options.
The bad one: use array of objects.
object[][] data;
Now you can put everything in that array, but it will be slow (boxing of value types) and untyped (hard to use and to maintain).
Instead of a jagged array, use tuples.
(int[] FlattenedImage, int Output)[] data;
That looks a little bit weird, but it's actually very useful. It's strongly typed, it prevents boxing, and it uses nice and modern language features.
The big problem here is you have an int and an int[]. So the [0] index of Data must itself be an array, rather than merely an integer. And since the [0] and [1] subscripts are different types, you're really gonna need a completely different kind of data structure here.
Here's an example using Tuples:
static IEnumerable<(int, int[])> CreateDataSet(string DatasetPath)
{
var result = new List<(int, int[])> = new List<(int, int[])>();
foreach(string line in File.ReadLines(DatasetPath))
{
var lineData = line.Split('|');
yield return (int.Parse(linedata[1]), FlattenArray(ImageToArray(lineData[0])) );
}
}
or with linq:
static IEnumerable<(int, int[])> CreateDataSet(string DatasetPath)
{
return File.ReadLines(DatasetPath).Select(line => {
var data = line.Split('|');
return ( int.Parse(data[1]), FlattenArray(ImageToArray(data[0])) );
});
}
If you would create a class or a struct to containt the data it would look something like this:
class ImageData
{
public int[] FlatImate { get; }
public int Number { get; }
public ImageData(int[] flatImage, int number)
{
FlatImage = flatImage;
Number = number;
}
}
static ImageData[] CreateDataSet(string datasetPath)
{
string[] lines = File.ReadAllLines(datasetPath);
ImageData[] data = new ImageData[Lines.GetUpperBound(0)];
for (int i = 0; i <= lines.GetUpperBound(0); i++)
{
string[] stringSplit = lines[i].Split('|');
int number = Convert.ToInt32(stringSplit[1]);
int[] flat = FlattenArray(ImagetoArray(StringSplit[0]));
data[i] = new ImageData(flat, number);
}
return data;
}

Add one column of 2D array to listbox using AddRange

I have one 2D array:
string[,] table = new string[100,2];
and I want to add the table[,0] to a listbox, something like that
listbox1.Items.AddRange(table[,0]);
What is the trick to do that?
Edit: I want to know if it possible to do that using AddRange
For readability you can create extension method for an array.
public static class ArrayExtensions
{
public static T[] GetColumn<T>(this T[,] array, int columnNum)
{
var result = new T[array.GetLength(0)];
for (int i = 0; i < array.GetLength(0); i++)
{
result[i] = array[i, columnNum];
}
return result;
}
}
Now you can easily add ranges as slices from array. Note that you create a copy of elements from original array.
listbox1.Items.AddRange(table.GetColumn(0));

Passing one Dimension of a Two Dimensional Array in C#

I have moved from C to C#.
I have a function which accepts an array. I want to pass one dimension of a Two Dimensional array to this function.
C Code would be:-
void array_processing(int * param);
void main()
{
int Client_ID[3][50];
/* Some
Processing
which fills
this array */
array_processing(&Client_ID[1]);
}
Now, When I want to do same in C#, How can I pass this array?
Function defination will look like:-
private void array_processing(ref int[] param);
and Array would be declared as :-
int[,] Client_ID = new int[3,50];
Now How can I pass Client_ID[1] to the function array_processing()??
By doing array_processing ( ref Client_ID[1]) shouts as "Wrong Number of Indices"!
You can't really do that. C# is less outgoing about its arrays, and prevents you from doing C-like manipulations. This is a good thing.
You have various options:
Create a 1D array and copy your 2D row to it.
Use a jagged array - an array of arrays, which is more like what C lets you do.
Have an array_processing overload that takes a 2D array and a row number.
If you really want to access a 2D row as a 1D array, you should create a 'RowProxy' class that will implement the IList interface and let you access just one row:
class RowProxy<T>: IList<T>
{
public RowProxy(T[,] source, int row)
{
_source = source;
_row = row;
}
public T this[int col]
{
get { return _source[_row, col]; }
set { _source[_row, col] = value; }
}
private T[,] _source;
private int _row;
// Implement the rest of the IList interface
}
Use a lambda expression that will lose the array semantics, but is rather cool:
var ClientId = ...;
var row_5_accessor = (c=>ClientId[5, c]);
You can use row_5_accessor as a function, row_5_accessor(3) will give you ClientId[5, 3]
You can use a jagged array
// Initialize jagged array
int[][] clientID = new int[3][];
for (int i=0; i<clientId.Length; i++)
{
clientId[i] = new int[50];
}
array_processing(ref clientId[1]);
And your method:
private void array_processing(ref int[] subArray);
Just declare method
private void ParseArray(int[,] ar)
{
// Some work...
}
UDP: Code format
A primitive way would be:
var dimNumber = 1;
int[] oneDimension = new int[50];
for(var i=0; i<50; i++)
{
oneDimension[i] = Client_ID[dimNumber][i];
}
array_processing ( ref oneDimension);
I would suggest using Lambda expressions like in the way 5 of zmbq's answer.
You could declare you array as
int[][] Client_ID = new[] { new int[50], new int[50], new int[50] };
and then you can pass it to your array_processing function
array_processing(ref Clinet_ID[1]);
Sorry for miss of my pen.
Late to the conversation, but here is a jagged array example to do this:
string[][] rows = GetStringArray(values);
string[] row = rows[0];
You would set up your jagged array something like:
// rowCount from runtime data
stringArray = new string[rowCount][];
for (int index = 0; index < rowCount; index++)
{
// columnCount from runtime data
stringArray[index] = new string[columnCount];
for (int index2 = 0; index2 < columnCount; index2++)
{
// value from runtime data
stringArray[index][index2] = value;
}
}

How to delete a row from a 2d array in c#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Delete row of 2D string array in C#
i have a 2d string array, I want to delete a specified row from the array.
string[] a = new string[] { "a", "b" }; //dummy string array
int deleteIndex = 1; //we want to "delete" element in position 1 of string
a = a.ToList().Where(i => !a.ElementAt(deleteIndex).Equals(i)).ToArray();
dirty but gives the expected result (foreach through the array to test it)
EDIT missed the "2d array" detail, here is the right code for the job
string[][] a = new string[][] {
new string[] { "a", "b" } /*1st row*/,
new string[] { "c", "d" } /*2nd row*/,
new string[] { "e", "f" } /*3rd row*/
};
int rowToRemove = 1; //we want to get rid of row {"c","d"}
//a = a.ToList().Where(i => !i.Equals(a.ElementAt(rowToRemove))).ToArray(); //a now has 2 rows, 1st and 3rd only.
a = a.Where((el, i) => i != rowToRemove).ToArray(); // even better way to do it maybe
code updated
As has been said above you cant remove from an array.
If you are going to need to remove rows quite often maybe change from using a 2d array to a list containing an array of string. This way you can make use of the remove methods that list implements.
Ok so I said you can't "delete" them. That's still true. You'll have to create a new array instance with enough space for the items you want to keep and copy them over.
If this is a jagged array, using LINQ here could simplify this.
string[][] arr2d =
{
new[] { "foo" },
new[] { "bar", "baz" },
new[] { "qux" },
};
// to remove the second row (index 1)
int rowToRemove = 1;
string[][] newArr2d = arr2d
.Where((arr, index) => index != rowToRemove)
.ToArray();
// to remove multiple rows (by index)
HashSet<int> rowsToRemove = new HashSet<int> { 0, 2 };
string[][] newArr2d = arr2d
.Where((arr, index) => !rowsToRemove.Contains(index))
.ToArray();
You could use other LINQ methods to remove ranges of rows easier (e.g., Skip(), Take(), TakeWhile(), etc.).
If this is a true two-dimensional (or other multi-dimensional) array, you won't be able to use LINQ here and will have to do it by hand and it gets more involved. This still applies to the jagged array as well.
string[,] arr2d =
{
{ "foo", null },
{ "bar", "baz" },
{ "qux", null },
};
// to remove the second row (index 1)
int rowToRemove = 1;
int rowsToKeep = arr2d.GetLength(0) - 1;
string[,] newArr2d = new string[rowsToKeep, arr2d.GetLength(1)];
int currentRow = 0;
for (int i = 0; i < arr2d.GetLength(0); i++)
{
if (i != rowToRemove)
{
for (int j = 0; j < arr2d.GetLength(1); j++)
{
newArr2d[currentRow, j] = arr2d[i, j];
}
currentRow++;
}
}
// to remove multiple rows (by index)
HashSet<int> rowsToRemove = new HashSet<int> { 0, 2 };
int rowsToKeep = arr2d.GetLength(0) - rowsToRemove.Count;
string[,] newArr2d = new string[rowsToKeep, arr2d.GetLength(1)];
int currentRow = 0;
for (int i = 0; i < arr2d.GetLength(0); i++)
{
if (!rowsToRemove.Contains(i))
{
for (int j = 0; j < arr2d.GetLength(1); j++)
{
newArr2d[currentRow, j] = arr2d[i, j];
}
currentRow++;
}
}
Instead of array you can use List or ArrayList class. Using it you can dynamically add element and remove based on your requirement. Array is fixed in size, which can not be manipulated dynamically.
The best way is to work with a List<Type>! The items are ordered in the way the are added to the list and each of them can be deleted.
Like this:
var items = new List<string>;
items.Add("One");
items.Add("Two");
items.RemoveAt(1);

Remove Element From Array by String (text) instead of Index

I want to remove the element form the array. Actually I don't know the the index of the element and want to remove through it's value. I have tried a lot but fail. This is the function which i used to add element in the Array
string [] Arr;
int i = 0;
public void AddTOList(string ItemName)
{
Arr[i] = ItemName;
i++;
}
And I want to remove the element by the value. I know the below function is wrong but I want to explain what I want:
public void RemoveFromList(string ItemName)
{
A["Some_String"] = null;
}
Thanks
If you want to remove items by a string key then use a Dictionary
var d = new Dictionary<string, int>();
d.Add("Key1", 3);
int t = d["Key1"];
Or something like that.
Array has a fixed size, which is not suitable for your requirement. Instead you can use List<string>.
List<string> myList = new List<string>();
//add an item
myList.Add("hi");
//remove an item by its value
myList.Remove("hi");
List<string> list = new List<string>(A);
list.Remove(ItemName);
A = list.ToArray();
and #see Array.Resize
and #see Array.IndexOf
You can iterate through every value in array and if found then remove it. Something like this
string[] arr = new string[] { "apple", "ball", "cat", "dog", "elephant", "fan", "goat", "hat" };
string itemToRemove = "fan";
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == itemToRemove)
{
arr[i]=null;
break;
}
}

Categories

Resources