// Load data public void LoadData( Array array ) { // this.array = array; // set column and row headers FixedRows = 1; FixedColumns = 1; // Redim the grid Redim( array.GetLength( 0 ) + FixedRows, array.GetLength( 1 ) + FixedColumns ); // Col Header Cell Template columnHeader = new CellColumnHeaderTemplate( ); columnHeader.BindToGrid( this ); // Row Header Cell Template rowHeader = new CellRowHeaderTemplate( ); rowHeader.BindToGrid( this ); // Header Cell Template (0,0 cell) cellHeader = new CellHeaderTemplate( ); cellHeader.BindToGrid( this ); // Data Cell Template dataCell = new CellArrayTemplate( array ); ; dataCell.BindToGrid( this ); RefreshCellsStyle( ); }
private void CheckGameOver() { switch (Clp.gameStatus) { case ClopWar.GAME_BLUEWON: MessageBox.Show("BLUE won!"); if (StratFiles.GetLength(0) > 0) { LoadStrat(); } Debug_quit = true; Clp.ResetGame(); break; case ClopWar.GAME_REDWON: MessageBox.Show("RED won!"); if (StratFiles.GetLength(0) > 0) { LoadStrat(); } Clp.ResetGame(); Debug_quit = true; break; } }
public static string CodeRepresentation(Array a) { StringBuilder ret = new StringBuilder(); ret.Append(a.GetType().FullName); ret.Append("("); switch (a.Rank) { case 1: { for (int i = 0; i < a.Length; i++) { if (i > 0) ret.Append(", "); ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0)))); } } break; case 2: { int imax = a.GetLength(0); int jmax = a.GetLength(1); for (int i = 0; i < imax; i++) { ret.Append("\n"); for (int j = 0; j < jmax; j++) { if (j > 0) ret.Append(", "); ret.Append(Ops.StringRepr(a.GetValue(i + a.GetLowerBound(0), j + a.GetLowerBound(1)))); } } } break; default: ret.Append(" Multi-dimensional array "); break; } ret.Append(")"); return ret.ToString(); }
/// <summary> /// [拡張]Rangeクラスのオブジェクトを文字列配列に変換します。 /// </summary> /// <returns>文字列配列を返します。</returns> public static string[,] DeepToString(this Excel.Range range) { if (range == null) { throw new ArgumentNullException(); } if (range.Cells.Value == null || range.Cells.Value.GetType() == typeof(String)) { throw new ArgumentException("Rangeオブジェクトが単一セルです。"); } //Excel.RangeオブジェクトをSystem.Arrayオブジェクトに変換します。 System.Array tmpArr = (System.Array)range.Cells.Value; //変換先の文字列配列を用意します。 string[,] ret = new string[tmpArr.GetLength(0), tmpArr.GetLength(1)]; //2次元配列の1列目の各行を文字列に変換して、返り値の配列に代入します。 for (int i = 1; i <= tmpArr.GetLength(0); i++) { for (int j = 1; j <= tmpArr.GetLength(1); j++) { if (tmpArr.GetValue(i, j) == null) { ret[i - 1, j - 1] = ""; } else { ret[i - 1, j - 1] = (string)tmpArr.GetValue(i, j).ToString(); } } } return(ret); }
public void WriteArray(System.Array _array) { // Initialise with symbol to indicate start of array StringBuilder.Append('['); switch (_array.Rank) { case 1: int _1DArrayLength = _array.Length; for (int _iter = 0; _iter < _1DArrayLength; _iter++) { if (_iter != 0) { StringBuilder.Append(','); } WriteObjectValue(_array.GetValue(_iter)); } break; case 2: int _outerArrayLength = _array.GetLength(0); int _innerArrayLength = _array.GetLength(1); for (int _outerIter = 0; _outerIter < _outerArrayLength; _outerIter++) { if (_outerIter != 0) { StringBuilder.Append(','); } // Append symbol to indicate start of json string representation of inner array StringBuilder.Append('['); for (int _innerIter = 0; _innerIter < _innerArrayLength; _innerIter++) { if (_innerIter != 0) { StringBuilder.Append(','); } WriteObjectValue(_array.GetValue(_outerIter, _innerIter)); } // Append symbol to indicate end of json string representation of inner array StringBuilder.Append(']'); } break; } // Append symbol to indicate end of json string representation of array StringBuilder.Append(']'); return; }
public virtual void LoadDataSource(System.Array p_Array, GridArrayStyle p_Style, SourceGrid2.Cells.Virtual.CellVirtual p_CellDataTemplate, SourceGrid2.Cells.Virtual.CellVirtual p_CellColumnHeader, SourceGrid2.Cells.Virtual.CellVirtual p_CellRowHeader, SourceGrid2.Cells.Virtual.CellVirtual p_CellHeader) { m_Style = p_Style; m_Array = p_Array; if ((p_Style & GridArrayStyle.ColumnHeaderIndex) == GridArrayStyle.ColumnHeaderIndex) { FixedRows = 4; } else { FixedRows = 0; } if ((p_Style & GridArrayStyle.RowHeaderIndex) == GridArrayStyle.RowHeaderIndex) { FixedColumns = 1; } else { FixedColumns = 0; } Redim(m_Array.GetLength(0) + FixedRows, m_Array.GetLength(1) + FixedColumns); //Col Header Cell Template m_ColHeaderCell = p_CellColumnHeader; m_ColHeaderCell.BindToGrid(this); //Row Header Cell Template m_RowHeaderCell = p_CellRowHeader; m_RowHeaderCell.BindToGrid(this); //Header Cell Template (0,0 cell) m_HeaderCell = p_CellHeader; m_HeaderCell.BindToGrid(this); //Data Cell Template m_DataCell = p_CellDataTemplate; m_DataCell.BindToGrid(this); }
// The test guarantees that `a` is a 2-D array. Verifies that the intrinsics don't kick in. static void test3(System.Array a) { Console.WriteLine(a.Rank); Console.WriteLine(a.GetLength(0)); Console.WriteLine(a.GetLength(1)); Console.WriteLine(a.GetLowerBound(0)); Console.WriteLine(a.GetUpperBound(0)); Console.WriteLine(a.GetLowerBound(1)); Console.WriteLine(a.GetUpperBound(1)); }
/// <summary> /// 导入Bom单主表资料 /// </summary> /// <param name="values"></param> private void ImportBom(System.Array values) { int len1 = values.GetLength(0); int len2 = values.GetLength(1); DataLib.DataHelper myHelper = new DataLib.DataHelper(); DataSet dsBom = myHelper.GetDs("select * from t_Bom"); System.Data.DataTable dt = dsBom.Tables[0]; System.Data.DataTable dtTmp = dt.Copy(); dt.Columns["F_BillID"].Unique = true; string strID; try { for (int i = 1; i < len1; i++) { strID = values.GetValue(i, 1).ToString(); if (strID.Length == 0) { continue; } if (dt.Select("F_BillID = '" + strID + "'").Length > 0) { MessageBox.Show(this, "数据库已存在编码为'" + strID + "'的BOM单号,请检查待导入Excel文件!", "提示"); break; } DataRow drNew = dsBom.Tables[0].NewRow(); drNew["F_BillID"] = values.GetValue(i, 1).ToString(); if (values.GetValue(i, 2).ToString().Length == 0) { drNew["F_Date"] = "1900-1-1"; } else { drNew["F_Date"] = values.GetValue(i, 2).ToString(); } drNew["F_ItemID"] = values.GetValue(i, 3).ToString(); drNew["F_Remark"] = values.GetValue(i, 4).ToString(); dsBom.Tables[0].Rows.Add(drNew); } myHelper.SaveData(dsBom, "select * from t_Bom"); } catch (Exception E) { MessageBox.Show(this, E.Message, "错误"); } }
public Shape ConvertArrayToShape(Array data) { width = data.GetLength(1); height = data.GetLength(0); shape = new Shape(); double[] prevRow = ReadRow(data, 0); for (int y = 1; y < height; y++) { double[] nextRow = ReadRow(data, y); Vertex[] verts = GetRowOfVertices(nextRow, prevRow, y - 1); shape.Vertices.AddRange(verts); prevRow = nextRow; } return shape; }
private static int EnumCheckbox(string label, object enumObj, string defaultName, object defaultVal, object valOnZero, bool ignoreNone = true, bool ignoreAll = true) { if (!enumObj.GetType().IsEnum) { throw new ArgumentException("enumObj must be an enum."); } // Convert enum value to an int64 so we can treat it as a flag set int enumFlags = Convert.ToInt32(enumObj); EditorGUILayout.BeginVertical(EditorStyles.helpBox); EditorGUILayout.LabelField(label, EditorStyles.miniLabel); GUIStyle styleHR = new GUIStyle(GUI.skin.box); styleHR.stretchWidth = true; styleHR.fixedHeight = 2; GUILayout.Box("", styleHR); System.Array enumVals = Enum.GetValues(enumObj.GetType()); int lastvalue = Convert.ToInt32(enumVals.GetValue(enumVals.GetLength(0) - 1)); foreach (object enumVal in enumVals) { int flagVal = Convert.ToInt32(enumVal); if (ignoreNone && flagVal == 0 && enumVal.ToString().ToLower() == "none") { continue; } if (ignoreAll && flagVal == lastvalue && enumVal.ToString().ToLower() == "all") { continue; } bool selected = (flagVal & enumFlags) != 0; selected = EditorGUILayout.Toggle(enumVal.ToString(), selected); // If it's selected add it to the enumObj, otherwise remove it if (selected) { enumFlags |= flagVal; } else { enumFlags &= ~flagVal; } } if (!string.IsNullOrEmpty(defaultName)) { if (GUILayout.Button(defaultName, EditorStyles.miniButton)) { enumFlags = Convert.ToInt32(defaultVal); } } EditorGUILayout.EndVertical(); if (enumFlags == 0) { enumFlags = Convert.ToInt32(valOnZero); } return(enumFlags); }
static long ArrayLength(Array array, int i) { long n = 1; for ( ; i < array.Rank; i++ ) n *= array.GetLength(i); return n; }
/// <summary> /// This routine searches all the elements equal to obj in array; /// the result is indices where obj are situated in the array /// </summary> /// <param name="obj">the object to search</param> /// <param name="array">array in which this function is searching</param> /// <returns></returns> public static Int32[] find(object obj, System.Array array) { int n = array.GetLength(0); int res_n = 0; int i; for (i = 0; i < n; i++) { if (array.GetValue(i).Equals(obj)) { res_n++; } } if (res_n == 0) { return(null); } Int32[] res = new Int32[res_n]; i = 0; for (int j = 0; j < res_n; j++) { while (!(array.GetValue(i).Equals(obj))) { i++; } res[j] = i++; } return(res); }
//-------------------------------------------------------------------// /// <summary> /// Converts COM like 2dim array where one dimension is of length 1 to regular array. /// </summary> /// <param name="a">COM array</param> /// <returns>regular array</returns> public static object[] Com2DArray2Array(Array a) { if (a == null) return null; object[] converted = null; switch (a.Rank) { case 1: converted = new object[a.GetLength(0)]; for (var i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { converted[i] = a.GetValue(i); } break; case 2: { var d1 = a.GetLength(0); var d2 = a.GetLength(1); var len = (d1 > d2) ? d1 : d2; converted = new object[len]; var dim = (d1 > d2) ? 0 : 1; for (var i = a.GetLowerBound(dim); i <= a.GetUpperBound(dim); i++) { converted[i - a.GetLowerBound(dim)] = a.GetValue((d1 == 1 ? a.GetLowerBound(0) : i), (d2 == 1 ? a.GetLowerBound(1) : i)); } } break; } return converted; }
public string Test() { string filepath = ""; try { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); filepath = "http://naccounting.net" + @"/Content/FUELEXCL.xls"; Microsoft.Office.Interop.Excel.Workbook wbook = null; Microsoft.Office.Interop.Excel.Worksheet wsheet = null; Range range = null; app.Visible = false; //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); wbook = app.Workbooks.Open(filepath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); string currentSheet = "FUELEXCL"; wsheet = (Worksheet)wbook.Worksheets.get_Item(currentSheet); range = wsheet.get_Range("A1", "A7"); System.Array myvalues = (System.Array)range.Cells.Value2; return(filepath + "---" + myvalues.GetLength(1).ToString()); } catch (Exception ex) { return(ex.ToString() + "\n\n\r" + filepath); } }
// This is the GENERIC Type constructor. protected CombinatorialBase(Array arrayObjects, int nKlass) { // Check the validity of the arguments DoArgumentCheck(arrayObjects.Length, nKlass); m_nKlass = nKlass; // Always takes the ZERO (FIRST) dimension of the array. There is no // problem in manipulation multidimensional arrays. m_nMaxIndex = arrayObjects.GetLength(0) - 1; m_arrayIndeces = new int[m_nKlass]; m_arrayIndecesDummy = new int[m_nKlass]; m_arrayCurrentObj = new TouchPoint2[m_nKlass]; // m_arrayCurrentCombination = Array.CreateInstance( // arrayObjects.GetValue(0).GetType(), m_nKlass); // Make a shallow copy of the source array. // m_arrayObj = Array.CreateInstance( arrayObjects.GetValue(0).GetType(), arrayObjects.Length); //m_arrayObj = Array.CreateInstance(Type.GetType("System.Object"), arrayObjects.Length); //Array.Copy(arrayObjects, m_arrayObj, arrayObjects.Length); //TODO: review code m_arrayObj = new TouchPoint2[arrayObjects.Length]; Array.Copy(arrayObjects, m_arrayObj, arrayObjects.Length); }
private static Digit BuildDigitsRepresentingAllIndices(Array subjectAsArray) { return Enumerable .Range(0, subjectAsArray.Rank) .Reverse() .Aggregate((Digit) null, (next, rank) => new Digit(subjectAsArray.GetLength(rank), next)); }
static void ArrayInfo(String name, Array a) { Console.Write("{0} has length={1} rank={2} [", name, a.Length, a.Rank); for (int i = 0, stop=a.Rank; i<stop; i++) Console.Write(" {0}", a.GetLength(i)); Console.WriteLine(" ]"); }
static void AssertArray(Array array, params object[] expectedValues) { Program.Assert(array.GetLength(0) == expectedValues.Length, "The arrays lengths are differents"); for (int i = 0; i < expectedValues.Length; i++) { Program.Assert(array.GetValue(i).Equals(expectedValues[i]), "Unexpected values"); } }
// Load data public void LoadData( Array array ) { // this.array = array; behavior = new CellBehavior( array ); // set column and row headers FixedRows = 1; FixedColumns = 1; // Redim the grid Redim( array.GetLength( 0 ) + FixedRows, array.GetLength( 1 ) + FixedColumns ); // Header this[0, 0] = new Header( ); // Column headers for ( int i = 1; i < this.ColumnsCount; i++ ) { ColumnHeader header = new ColumnHeader( i.ToString( ) ); header.EnableSort = false; this[0, i] = header; } // Row headers for ( int i = 1; i < this.RowsCount; i++ ) { this[i, 0] = new RowHeader( i.ToString( ) ); } // Data cells Type type = array.GetValue( 0, 0 ).GetType( ); for ( int i = 1, ia = 0; i < this.RowsCount; i++, ia++ ) { for ( int j = 1, ja = 0; j < this.ColumnsCount; j++, ja++ ) { Cell cell = new Cell( array.GetValue( ia, ja ), type ); cell.Behaviors.Add( behavior ); this[i, j] = cell; } } Colorize( ); }
public ArrayTraverse(Array array) { this.Position = new int[array.Rank]; this.maxLengths = new int[array.Rank]; for (int i = 0; i < array.Rank; i++) { this.maxLengths[i] = array.GetLength(i) - 1; } }
private static int[] GetMultidimensionalIndices(System.Array a, int idx) { var indices = new int[a.Rank]; for (var i = 0; i < a.Rank; i++) { var div = 1; for (var j = i + 1; j < a.Rank; j++) { div *= a.GetLength(j); } indices[i] = a.GetLowerBound(i) + idx / div % a.GetLength(i); } return(indices); }
public ArrayTraverse(Array array) { _maxLengths = new int[array.Rank]; for (int i = 0; i < array.Rank; ++i) { _maxLengths[i] = array.GetLength(i) - 1; } Position = new int[array.Rank]; }
public static void AddItemToArray(object item, System.Array array) { int arraySize = array.GetLength(0); Array tempArray = Array.CreateInstance(item.GetType(), arraySize + 1); array.CopyTo(tempArray, 0); array = tempArray; array.SetValue(item, arraySize); }
/// <summary> /// The array to string. /// </summary> /// <param name="array"> /// The array. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public static string ArrayToString(Array array) { StringBuilder text = new StringBuilder(); for (int i = 0; i < array.GetLength(0); i++) { if (i != array.GetLength(0) - 1) { text.Append(array.GetValue(i) + ", "); } else { text.Append(array.GetValue(i)); } } return text.ToString(); }
private static string CollectionToString(object collectionInstance, string propName, int layer) { //object collectionInstance = prop.GetValue(o, null); StringBuilder sb = new StringBuilder(); if (collectionInstance == null) { if (String.IsNullOrEmpty(propName)) { sb.AppendLayerFormatLine(layer, "[null]"); } else { sb.AppendLayerFormatLine(layer, "{0}: [null]", propName); } } else { if (!String.IsNullOrEmpty(propName)) { string strSize = ""; if (collectionInstance.GetType().IsArray) { System.Array ar = collectionInstance as System.Array; int rank = ar.Rank; StringBuilder ars = new StringBuilder(); for (int i = 0; i < rank; i++) { if (i != 0) { ars.Append("*"); } ars.Append(ar.GetLength(i)); } strSize = String.Format("[size: {0}]", ars.ToString()); } sb.AppendLayerFormatLine(layer, "{0}: {1}", propName, strSize); } foreach (object item in collectionInstance as IEnumerable) { if (IsBasicType(item.GetType()) || item == null) { sb.AppendLayerFormatLine(layer + 1, "[{0}]", item == null ? "null" : item.ToString()); } else { sb.AppendLayerFormatLine(layer + 1, "["); sb.Append(GeneralToString(item, layer + 2)); sb.AppendLayerFormatLine(layer + 1, "]"); } } } return(sb.ToString()); }
private void WriteArray(BinaryWriter bw, Array a, int dimension, params int[] indices) { if (a.Rank == dimension) WriteCore(bw, a.GetValue(indices)); else { for (int i = 0; i < a.GetLength(dimension); i++) WriteArray(bw, a, dimension + 1, indices.Append(i)); } }
/// <summary> /// 各次元のLengthを1/2した位置の要素を設定 /// </summary> public static void SetCenterValue(this Original.Array array, object value) { var indices = new int[array.Rank]; for (int i = 0; i < indices.Length; i++) { indices[i] = array.GetLength(i) / 2; } array.SetValue(value, indices); }
static public bool Equiv(System.Array a1, System.Array a2) { if (a1 == null) { return(a2 == null); } int len = a1.GetLength(0); return((len == a2.GetLength(0)) ? Equiv(a1, a2, len, 0, 0) : false); }
static public bool Equiv <T>(System.ArraySegment <T> a1, System.Array a2) { if (a2 == null) { return(a1.Array == null); } int len = a1.Count; return((len == a2.GetLength(0)) ? Equiv(a1.Array, a2, len, a1.Offset, 0) : false); }
private void serializeArray(Array array) { m_ArrayData = new object[array.Length]; m_ArrayDims = new int[array.Rank]; for(var i=0; i<array.Rank; i++) m_ArrayDims[i] = array.GetLength(i); var idx = 0; SerializationUtils.WalkArrayWrite(array, elm => m_ArrayData[idx++] = elm ); }
/// <summary> /// 各次元のLengthを1/2した位置の要素を取得 /// </summary> public static object GetCenterValue(this Original.Array array) { var indices = new int[array.Rank]; for (int i = 0; i < indices.Length; i++) { indices[i] = array.GetLength(i) / 2; } return(array.GetValue(indices)); }
private static int[] GetLengths(Array array) { var lengths = new int[array.Rank]; for (var i = 0; i < array.Rank; i++) { lengths[i] = array.GetLength(i); } return lengths; }
/// <summary> /// TRANSPOSE ARRAY /// </summary> /// <param name="pixelblock">PixelBlock of data values</param> /// <param name="noDataValue">Default NoData value</param> /// <returns>Array of values transposed</returns> internal static Array TransposeArray(IPixelBlock3 pixelblock, object noDataValue) { System.Array oldArray = (System.Array)pixelblock.get_PixelData(0); int cols = oldArray.GetLength(0); int rows = oldArray.GetLength(1); System.Array newArray = System.Array.CreateInstance(oldArray.GetType().GetElementType(), rows, cols); for (int col = 0; col < cols; col++) { for (int row = 0; row < rows; row++) { object noDataMaskValue = pixelblock.GetNoDataMaskVal(0, col, row); object pixelValue = (Convert.ToByte(noDataMaskValue, CultureInfo.InvariantCulture) == 1) ? oldArray.GetValue(col, row) : noDataValue; newArray.SetValue(pixelValue, row, col); } } return(newArray); }
public static int EnumCheckboxField <T>(string label, T enumObj, string defaultName, T defaultVal, T valOnZero, bool ignoreNone = true, bool ignoreAll = true) where T : struct, IConvertible { if (!typeof(T).IsEnum) { throw new ArgumentException("T must be an enum."); } // Convert enum value to an int64 so we can treat it as a flag set int enumFlags = Convert.ToInt32(enumObj); EditorGUILayout.BeginVertical(EditorStyles.helpBox); EditorGUILayout.LabelField(label, EditorStyles.miniLabel); DrawDivider(); System.Array enumVals = Enum.GetValues(typeof(T)); int lastvalue = Convert.ToInt32((T)enumVals.GetValue(enumVals.GetLength(0) - 1)); foreach (T enumVal in enumVals) { int flagVal = Convert.ToInt32(enumVal); if (ignoreNone && flagVal == 0 && enumVal.ToString().ToLower() == "none") { continue; } if (ignoreAll && flagVal == lastvalue && enumVal.ToString().ToLower() == "all") { continue; } bool selected = (flagVal & enumFlags) != 0; selected = EditorGUILayout.Toggle(enumVal.ToString(), selected); // If it's selected add it to the enumObj, otherwise remove it if (selected) { enumFlags |= flagVal; } else { enumFlags &= ~flagVal; } } if (!string.IsNullOrEmpty(defaultName)) { if (GUILayout.Button(defaultName, EditorStyles.miniButton)) { enumFlags = Convert.ToInt32(defaultVal); } } EditorGUILayout.EndVertical(); if (enumFlags == 0) { enumFlags = Convert.ToInt32(valOnZero); } return(enumFlags); }
private static PropertyDescriptorCollection CreateColumnPropertyDescriptorCollection(Array source) { var elementType = source.GetType().GetElementType(); var n = source.GetLength(0); var descriptors = new Array2DIndexPropertyDescriptor[n]; for (int i = 0; i < n; i++) { descriptors[i] = new Array2DIndexPropertyDescriptor(elementType, i); } return new PropertyDescriptorCollection(descriptors); }
static void Next(Array array, Int32[] indexer) { indexer[0]++; for (var i = 0; i < array.Rank - 1; ++i) { if (indexer[i] == array.GetLength(i)) { indexer[i ] = 0; indexer[i + 1]++; } } }
/// <summary> /// Initializes a new ArrayDataView from array with custom column names. /// </summary> /// <param name="array">array of data.</param> /// <param name="colnames">collection of column names.</param> public ArrayDataView(Array array, object[] colnames) : this(array) { if(colnames.Length != array.GetLength(1)) throw new ArgumentException("column names must correspond to array columns.","colnames"); _colnames = new string[colnames.Length]; for(int i = 0; i < colnames.Length; i++) { _colnames[i] = colnames[i].ToString(); } }
// General case: non-constant arguments to GetLength()/GetLowerBound()/GetUpperBound() static void test4(System.Array a) { int rank = a.Rank; Console.WriteLine(rank); for (int i = 0; i < rank; i++) { Console.WriteLine(a.GetLength(i)); Console.WriteLine(a.GetLowerBound(i)); Console.WriteLine(a.GetUpperBound(i)); } }
public void SetDesc(System.Array sourceArray) { _descriptor.Dimensions = (short)sourceArray.Rank; for (int i = 0; i < sourceArray.Rank; i++) { int lb = _descriptor.Bounds[i].LowerBound; int ub = sourceArray.GetLength(i) - 1 + lb; _descriptor.Bounds[i].UpperBound = ub; } }
private bool ArrayDimensionsEqual(Array a1, Array a2) { for (int dimension = 0; dimension < a1.Rank; dimension++) { if (a1.GetLength(dimension) != a2.GetLength(dimension)) { return false; } } return true; }
private void DimensionalWriteResoursy(ByteObjectWriter writer, Array array, Type itemType, int dimensional, int[] indexes) { for (int i = 0; i < array.GetLength(dimensional); i++) { indexes[dimensional] = i; if (dimensional < array.Rank - 1) DimensionalWriteResoursy(writer, array, itemType, dimensional + 1, indexes); else { writer.Complex(array.GetValue(indexes), itemType); } } }
private static PropertyDescriptorCollection CreateRowPropertyDescriptorCollection(Array source) { var elementType = source.GetType().GetElementType(); var n = source.GetLength(1); var descriptors = new Array2DIndexPropertyDescriptor[n]; for (int i = 0; i < n; i++) { descriptors[i] = new Array2DIndexPropertyDescriptor(elementType, i); } // ReSharper disable once CoVariantArrayConversion return new PropertyDescriptorCollection(descriptors); }
internal void Iterate_array_elements_in_all_dimensions(Array objectToFlatten, List<int> indexes) { var t = objectToFlatten.GetType(); if (t.GetArrayRank() > indexes.Count) for (var i = 0; i < objectToFlatten.GetLength(indexes.Count); i++) { indexes.Add(i); Iterate_array_elements_in_all_dimensions(objectToFlatten, indexes); indexes.RemoveAt(indexes.Count - 1); } else this.Element(objectToFlatten.GetValue(indexes.ToArray())); }
public static bool ExpData(System.Array Data, Excel.Range rDestStart) { try { Excel.Worksheet ws = rDestStart.Worksheet; Excel.Range rEnd = (Excel.Range)ws.Cells[Data.GetLength(0) + rDestStart.Row - 1, Data.GetLength(1) + rDestStart.Column - 1]; Excel.Range rg = ws.Range[rDestStart, rEnd]; rg.Value = Data; return(true); } catch (Exception ex) { _log.Fatal(ex); Console.WriteLine(ex.Message); return(false); } }
public int QueryValues(IRowBuffer row) { try { if (m_currentOGRFeature == null) { return(-1); } // loop and only set values in the rowbuffer // that were requested from the fieldMap int count = m_esriQueryFieldMap.GetLength(0); for (int i = 0; i < count; i++) { int esriFieldIndex = (int)m_esriQueryFieldMap.GetValue(i); // have to skip 1) objectid and 2) geometry field or we will get an ESRI // exception. Also have to skip anything that the query map is asking to ignore if (esriFieldIndex == -1 || esriFieldIndex == m_pDataset.get_OIDFieldIndex(0) || esriFieldIndex == m_pDataset.get_ShapeFieldIndex(0)) { continue; } try { IField valField = m_pDataset.get_Fields(0).get_Field(i); object val = m_pDataset.get_mapped_value(m_currentOGRFeature, i); row.set_Value(i, val); } catch (Exception ex) { // skip values that fail to be set but continue doing it anyway System.Diagnostics.Debug.WriteLine(ex.Message); } } return(m_currentOGRFeature.GetFID()); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return(-1); } }
// Save array to file public static void Save(string file, Array array) { StreamWriter writer = null; try { int height = array.GetLength(0); int width = array.GetLength(1); // create file writer = File.CreateText(file); // write array dimensions writer.WriteLine("{0} {1}", height, width); for (int i = 0; i < height; i++) { string[] strs = new string[width]; for (int j = 0; j < width; j++) { strs[j] = array.GetValue(i, j).ToString(); } writer.WriteLine(string.Join(" ", strs)); } } catch (Exception) { throw new ApplicationException(); } finally { // close file if (writer != null) writer.Close(); } }
/// <summary> /// Initializes a new ArrayDataView from array. /// </summary> /// <param name="array">array of data.</param> public ArrayDataView(Array array) { if (array.Rank != 2) throw new ArgumentException("Supports only two dimentional arrays","array"); _data = array; _rows = new ArrayRowView[array.GetLength(0)]; for(int i = 0; i < _rows.Length; i++) { _rows[i] = new ArrayRowView(this,i); } }
private void DimensionalReadResoursy(ByteObjectReader reader, Array array, Type itemType, int dimensional, int[] indexes) { for (int i = 0; i < array.GetLength(dimensional); i++) { indexes[dimensional] = i; if (dimensional < array.Rank - 1) DimensionalReadResoursy(reader, array, itemType, dimensional + 1, indexes); else { var item = reader.Complex(itemType); array.SetValue(item, indexes); } } }
private void LoadStrat() { //Get strategies filelist DirectoryInfo dir = new DirectoryInfo(Application.StartupPath + "\\strateg"); StratFiles = (Array)dir.GetFiles("*." + Clp.RecFileExt).Clone(); RndGen = new Random(DateTime.Now.Second); if (StratFiles.GetLength(0) > 0) { OwnStrat = null; //((FileInfo)(StratFiles.GetValue(RndGen.Next(StratFiles.GetUpperBound(0)+1)))).FullName; CPUStrat = ((FileInfo)(StratFiles.GetValue(RndGen.Next(StratFiles.GetUpperBound(0) + 1)))).FullName; ClpCPU.StrategyFile = CPUStrat; } }
private static IEnumerable <string> GetColumns(System.Array xlRange, int rownNumber) { int colCount = xlRange.GetLength(1); List <string> names = new List <string>(); for (int i = 1; i <= colCount; i++) { var name = GetValue(xlRange, rownNumber, i); //Just take the string before the line break. names.Add(name.Split('\n').FirstOrDefault()); } return(names.Where(s => !string.IsNullOrWhiteSpace(s))); }
/// <summary> /// [拡張]Rangeクラスのオブジェクトの指定された列(縦)を文字列配列に変換します。 /// </summary> /// <returns>1次元の文字列配列を返します。</returns> public static string[] ColumnToString(this Excel.Range range, int column) { if (range == null) { throw new ArgumentNullException(); } if (range.Cells.Value == null || range.Cells.Value.GetType() == typeof(String)) { throw new ArgumentException("Rangeオブジェクトが単一セルです。"); } //Excel.RangeオブジェクトをSystem.Arrayオブジェクトに変換します。 System.Array tmpArr = (System.Array)range.Cells.Value; if (column < 0 || tmpArr.GetLength(1) < column) { throw new ArgumentOutOfRangeException(); } //変換先の文字列配列を用意します。 string[] ret = new string[tmpArr.GetLength(0)]; //2次元配列の1列目の各行を文字列に変換して、返り値の配列に代入します。 for (int i = 1; i <= tmpArr.GetLength(0); i++) { if (tmpArr.GetValue(i, column) == null) { ret[i - 1] = ""; } else { ret[i - 1] = (string)tmpArr.GetValue(i, column).ToString(); } } return(ret); }
static public int GetLength(IntPtr l) { try { System.Array self = (System.Array)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); var ret = self.GetLength(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
/// <summary> /// Gets the array dimensions. /// </summary> /// <param name="ar">The array to return its dimensions.</param> /// <returns>the specified array's dimensions</returns> public static int[] GetArrayDimensions(object ar) { int[] dims = null; if (IsArray(ar.GetType())) { System.Array arObj = ar as System.Array; dims = new int[arObj.Rank]; for (int i = 0; i < dims.Length; i++) { dims[i] = arObj.GetLength(i); } } return(dims); }
static int GetLength(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); System.Array obj = (System.Array)ToLua.CheckObject(L, 1, typeof(System.Array)); int arg0 = (int)LuaDLL.luaL_checknumber(L, 2); int o = obj.GetLength(arg0); LuaDLL.lua_pushinteger(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
//проигрывает один клип из массива, выбирая случайным образом. Если клип уже звучит, то прерывает public void playClipsRandom(Array array) { if (array.Length == 0) { return; } AudioClip tmpClip =(AudioClip) array.GetValue(UnityEngine.Random.Range (0, array.GetLength (0))); if (tmpClip != null) { source.clip = tmpClip; source.Play (); } else { //Debug.LogError("soundControl:playClipsRandom: Clip not defined!!"); } }
//-------------------------------------------------------------------------------------------------------------- //проигрывает один клип из массива, выбирая случайным образом. Если клип уже звучит, то не прерывает public void playClipsRandomFull(Array array) { if (array.Length == 0) { return; } AudioClip tmpClip =(AudioClip) array.GetValue(UnityEngine.Random.Range (0, array.GetLength (0))); if (tmpClip != null) { if(!source.isPlaying){//если клип уже играет, то пусть играет source.clip = tmpClip; source.Play (); } } else { //Debug.LogError("soundControl:playClipsRandom: Clip not defined!!"); } }
private static bool HaveSameDimensions(object expectation, Array actual) { bool sameDimensions = true; for (int dimension = 0; dimension < actual.Rank; dimension++) { int expectedLength = ((Array) expectation).GetLength(dimension); int actualLength = actual.GetLength(dimension); sameDimensions = sameDimensions & AssertionScope.Current .ForCondition(expectedLength == actualLength) .FailWith("Expected dimension {0} to contain {1} item(s), but found {2}.", dimension, expectedLength, actualLength); } return sameDimensions; }
private void serialize( int[] coord, int dim, Array array, IProtocolFormatter writer ) { int dimLength = array.GetLength( dim ); writer.BeginWriteArray( dimLength ); for( int i = 0; i < dimLength; i++ ) { coord[ dim ] = i; if( dim == (array.Rank - 1) ) MessageWriter.writeObject( array.GetValue( coord ), writer ); else serialize( coord, dim + 1, array, writer ); } writer.EndWriteArray(); }
/// <summary> /// コンストラクタ /// 使用する配列構造を渡す /// 例) /// var array = new int[3, 4, 5]; /// var ai = new ArrayIndex(array); /// 等と記載する /// </summary> /// <param name="data">多次元配列</param> public ConvertArrayIndex( System.Array data ) { // 配列の個々の要素数を求める this._Length = new int[data.Rank]; for (int i = 0; i < this._Length.Length; i++) { this._Length[i] = data.GetLength(i); } // 配列の全要素数を求める this._TotalElementCounts = this._Length.Aggregate((now, next) => now * next); // 倍率配列を求める this._Mag = this.GetMagDimIndex(this._Length).ToArray(); }
public static object FitTypeForInternalUse(object o) { Core.DeReference(ref o); // leave a null unchanged if (o == null) { return(null); } // try to convert an integer type other than int to int if (o is uint || o is long || o is ulong || o is short || o is ushort || o is byte || o is sbyte || o is bool) { return(System.Convert.ToInt32(o)); } // try to convert a floating point type other than double to double else if (o is float || o is decimal) { return(System.Convert.ToDouble(o)); } // try to convert a string type other than string to string else if (o is char) { return(System.Convert.ToString(o)); } // try to convert an array type to Array else if (o.GetType().IsArray) { System.Array arr = (System.Array)o; ArrayList keys = new ArrayList(); ArrayList values = new ArrayList(); for (int i = 0; i < arr.GetLength(0); i++) { keys.Add(i); object value = arr.GetValue(i); // resursively fit type of current value values.Add(FitTypeForInternalUse(value)); } return(new Array(keys, values)); } // otherwise leave type unchanged else { return(o); } }