public RowSchema(SqlDataReader reader, string[] primaryKeyColumns)
 {
     _columns               = GetTableColumns(reader);
     PrimaryKeyColumns      = primaryKeyColumns.ToDictionary(c => c, c => ColumnNamesLookup[c]);
     RowEqualityComparer    = new RowComparer();
     RowKeyEqualityComparer = new RowKeyComparer();
 }
Exemple #2
0
        public TriggerData <TRow> ParseTriggerXml(XDocument body)
        {
            var root = body.Root;

            if (root == null)
            {
                throw new Exception("Document must have a root element.");
            }

            var inserted = root.XPathSelectElements("Inserted/row").Select(ParseRow).ToList();
            var deleted  = root.XPathSelectElements("Deleted/row").Select(ParseRow).ToList();

            var comparer = new RowComparer(this);

            var insertedRows = inserted.Except(deleted, comparer);
            var deletedRows  = deleted.Except(inserted, comparer);

            var modifiedRows = from i in inserted
                               join d in deleted on GetKey(i) equals GetKey(d)
                               select new RowChange <TRow>
            {
                OriginalValue = i, ModifiedValue = d
            };

            return(new TriggerData <TRow>
            {
                Application = root.XPathSelectElement("Application").Value,
                Date = DateTime.Parse(root.XPathSelectElement("Date").Value),
                TransactionId = root.XPathSelectElement("TransactionId").Value,
                User = root.XPathSelectElement("User").Value,
                Inserted = insertedRows.ToList(),
                Deleted = deletedRows.ToList(),
                Modified = modifiedRows.ToList(),
            });
        }
        private IReadOnlyList <object[]> SortInput()
        {
            var result = new List <object[]>();

            while (_input.Read())
            {
                var rowValues = new object[_spooledRowBuffer.SpooledCount];

                // First, we copy the input

                _input.RowBuffer.CopyTo(rowValues, 0);

                // Now we copy the remainder

                for (var i = 0; i < _outerSortEntries.Length; i++)
                {
                    var targetIndex = _input.RowBuffer.Count + i;
                    rowValues[targetIndex] = _outerSortEntries[i].GetValue();
                }

                result.Add(rowValues);
            }

            var rowComparer = new RowComparer(SortIndices, Comparers);

            result.Sort(rowComparer);
            return(result);
        }
Exemple #4
0
        public void should_compare_column_values_when_columns_exist()
        {
            var colName = "Test";
            var xRow    = new JsonGridRow
            {
                Columns = new List <JsonGridColumn> {
                    new JsonGridColumn {
                        Name = colName, Value = "Column 2"
                    }
                }
            };
            var yRow = new JsonGridRow
            {
                Columns =
                    new List <JsonGridColumn> {
                    new JsonGridColumn {
                        Name = colName, Value = "Column 1"
                    }
                }
            };

            RowComparer
            .CompareRows(colName, xRow, yRow)
            .ShouldEqual(1);
        }
Exemple #5
0
        DataSet ds = new DataSet(); //存放病人信息
        private void Dgv_Info_Sorted(object sender, EventArgs e)
        {
            if (Dgv_Info != null && lieMing == "床号")
            {
                DataTable                   dt          = ds.Tables[0];
                ListSortDirection           direction   = new ListSortDirection();
                Dictionary <int, SortOrder> sortColumns =
                    new Dictionary <int, SortOrder>();
                if (m == 0)
                {
                    RowComparer comp = new RowComparer(SortOrder.Ascending);
                    sortColumns.Add(0, SortOrder.Ascending);
                    direction = ListSortDirection.Ascending;
                    m         = 1;

                    comp.SortColumns = sortColumns;
                    var      query3 = dt.AsEnumerable().OrderBy(q => q, comp);
                    DataView dv3    = query3.AsDataView();
                    Dgv_Info.DataSource = dv3;
                }
                else
                {
                    RowComparer comp = new RowComparer(SortOrder.Descending);
                    sortColumns.Add(0, SortOrder.Descending);
                    direction = ListSortDirection.Descending;
                    m         = 0;

                    comp.SortColumns = sortColumns;
                    var      query3 = dt.AsEnumerable().OrderBy(q => q, comp);
                    DataView dv3    = query3.AsDataView();
                    Dgv_Info.DataSource = dv3;
                }
                Dgv_Info.Columns["床号"].HeaderCell.SortGlyphDirection = direction == ListSortDirection.Ascending ? SortOrder.Ascending : SortOrder.Descending;
            }
        }
        public void TestDimensionKey()
        {
            var schema = CreateSchema(
                new Field {
                ValueType = typeof(int), FieldType = FieldType.Dimension,
            },
                new Field {
                ValueType = typeof(int), FieldType = FieldType.Dimension,
            },
                new Field {
                ValueType = typeof(int), FieldType = FieldType.Fact,
            });

            var row1 = new object[] { 1, 1, 1 };
            var row2 = new object[] { 1, 1, 4 };
            var row3 = new object[] { 1, 2, 1 };

            var comparer = new RowComparer(schema);

            Assert.IsTrue(comparer.Equals(row1, row2));
            Assert.IsFalse(comparer.Equals(row1, row3));

            Assert.IsTrue(comparer.Compare(row1, row2) == 0);
            Assert.IsTrue(comparer.Compare(row1, row3) == -1);
            Assert.IsTrue(comparer.Compare(row3, row2) == 1);
        }
 public RowSchema(string connectionString, SqlObjectName tableName, string[] primaryKeyColumns)
 {
     _columns               = GetTableColumns(connectionString, tableName);
     PrimaryKeyColumns      = (primaryKeyColumns ?? connectionString.GetPrimaryKeyColumns(tableName)).ToDictionary(c => c, c => ColumnNamesLookup[c]);
     RowEqualityComparer    = new RowComparer();
     RowKeyEqualityComparer = new RowKeyComparer();
 }
        public void TestMulti()
        {
            var schema = CreateSchema(
                new Field { ValueType = typeof(string), FieldType = FieldType.Key },
                new Field { ValueType = typeof(int), FieldType = FieldType.Key },
                new Field { ValueType = typeof(DateTime?), FieldType = FieldType.Key },
                new Field { ValueType = typeof(int), FieldType = FieldType.Fact });

            var row1 = new object[] { "A", 1, null, 37 };
            var row2 = new object[] { "A", 1, null, 11 };
            var row3 = new object[] { "B", 1, null, 3 };
            var row4 = new object[] { "B", 1, new DateTime(2000, 1, 1), 9 };
            var row5 = new object[] { "B", 1, new DateTime(2000, 1, 1), 11 };
            var row6 = new object[] { "B", 1, new DateTime(2000, 1, 2), 3 };
            var row7 = new object[] { "B", 2, new DateTime(2000, 1, 2), 2 };
            var row8 = new object[] { "C", 19, new DateTime(2000, 1, 2), 2 };

            var comparer = new RowComparer(schema);
            Assert.IsTrue(comparer.Equals(row1, row2));
            Assert.IsFalse(comparer.Equals(row1, row4));
            Assert.IsTrue(comparer.Equals(row4, row5));
            Assert.IsFalse(comparer.Equals(row3, row4));

            Assert.IsTrue(comparer.Compare(row1, row2) == 0);
            Assert.IsTrue(comparer.Compare(row1, row3) == -1);
            Assert.IsTrue(comparer.Compare(row3, row2) == 1);
            Assert.IsTrue(comparer.Compare(row4, row3) == 1);
            Assert.IsTrue(comparer.Compare(row3, row4) == -1);
            Assert.IsTrue(comparer.Compare(row4, row5) == 0);
            Assert.IsTrue(comparer.Compare(row5, row6) == -1);
            Assert.IsTrue(comparer.Compare(row6, row7) == -1);
            Assert.IsTrue(comparer.Compare(row7, row8) == -1);
        }
Exemple #9
0
            public void CustomSort(RowComparer rowComparer)
            {
                Debug.Assert(rowComparer is not null);
                Debug.Assert(Count > 0);

                this.rowComparer = rowComparer;
                CustomQuickSort(0, Count - 1);
            }
Exemple #10
0
        public void should_return_zero_when_comparing_rows_if_column_does_not_exist()
        {
            var xRow = new JsonGridRow();
            var yRow = new JsonGridRow();

            RowComparer
            .CompareRows("Test", xRow, yRow)
            .ShouldEqual(0);
        }
        private void sortToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var sortForm = new frmSort();

            var colHeaders = new List <Tuple <string, string, int> >();
            int i          = 0;

            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                colHeaders.Add(new Tuple <string, string, int>(col.Name, col.HeaderText, i++));
            }

            sortForm.Populate(colHeaders);
            sortForm.ShowDialog();
            if (DialogResult.Yes == sortForm.DialogResult)
            {
                DataTable     dtSort      = (DataTable)dataGridView1.DataSource;
                RowComparer   rowComparer = new RowComparer(SortOrder.Ascending, sortForm.SortedFields);
                StringBuilder sortBuilder = new StringBuilder();
                foreach (frmSort.SortItem sortField in sortForm.SortedFields)
                {
                    if (sortBuilder.Length > 0)
                    {
                        sortBuilder.Append(" , ");
                    }
                    sortBuilder.Append(sortField.val);
                }

                dtSort.DefaultView.Sort = sortBuilder.ToString();
                //var metaDataRows = (DataTable)dataGridView1.DataSource;
                //dataGridView1.DataSource = null;
                //RowComparer rc = new RowComparer(SortOrder.Ascending, sortForm.SortedFields);
                //switch (sortForm.SortedFields.Count)
                //{
                //	case 1:
                //	{
                //		metaDataRows.Sort( (x,y) =>
                //		{
                //			Type m = metaDataRows[0].GetType();
                //			PropertyInfo p1Info = m.GetProperty(sortForm.SortedFields[0].val);
                //			var gMethod = p1Info.GetGetMethod();
                //			string x1 = (string) gMethod.Invoke(x, null);
                //			string y1 = (string) gMethod.Invoke(y, null);
                //			return string.Compare(x1, y1);
                //		});
                //	}
                //		break;
                //}

                ////sortForm.SortedFields
                ////metaDataRows.Sort(rc);
                //dataGridView1.DataSource = metaDataRows;
                ////dataGridView1.Sort( new RowComparer(SortOrder.Ascending, sortForm));
            }
        }
Exemple #12
0
        public void Sort(int colIndex)
        {
            // If the sort column has changed, force ascending sort.
            // Otherwise, toggle the sort order.
            if (_col == colIndex)
            {
                // Sorting same column again. Toggle the sort order.
                _sortAscending = !_sortAscending;
            }
            else
            {
                // Sorting a different column.  Use ascending sort
                // and switch to the appropriate RowComparer for the column.
                _sortAscending = true;
                _col           = colIndex;
                _comparer      = _listView.Columns[colIndex].Tag as RowComparer;

                if (_comparer == null)
                {
                    _comparer = _defaultComparer;
                }
            }

            // The list view tends to sort automatically when
            // ListView.Sorting or ListView.ListViewItemSorter changes.
            // It's a little unpredictable, so we use _didSort to keep
            // track of whether the sort occurs or not (Comparer sets
            // it to true).
            _didSort = false;

            // Always set _listView.Sorting because some users set it
            // to None between sorts to cause new items to appear
            // at the bottom.  This sometimes initiates the sort, setting _didSort to true.
            if (_sortAscending)
            {
                _listView.Sorting = SortOrder.Ascending;
            }
            else
            {
                _listView.Sorting = SortOrder.Descending;
            }

            // This assignment sometimes initiates the sort, like it or not.
            _listView.ListViewItemSorter = this;

            // Avoid re-sorting unnecessarily, but make sure
            // it happens at least once.
            if (!_didSort)
            {
                // This results in multiple calls to Compare().
                _listView.Sort();
            }
        } // Sort
 public StringConvertibleMatrixView()
 {
     InitializeComponent();
     ShowRowsAndColumnsTextBox  = true;
     ShowStatisticalInformation = true;
     errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
     errorProvider.SetIconPadding(rowsTextBox, 2);
     errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
     errorProvider.SetIconPadding(columnsTextBox, 2);
     sortedColumnIndices = new List <KeyValuePair <int, SortOrder> >();
     rowComparer         = new RowComparer();
 }
        public override IAccumulator Sort(IEnumerable <string> otherBoundVariables)
        {
            List <int> sortColumns;

            if (SortRequired(otherBoundVariables, out sortColumns))
            {
                var comparer = new RowComparer(sortColumns);
                _rows.Sort(comparer);
            }
            SortOrder = new List <int>(sortColumns);
            return(this);
        }
Exemple #15
0
        private DataTable SortColumn(DataTable dt, int index, SortOrder sort)
        {
            Dictionary <int, SortOrder> sortColumns = new Dictionary <int, SortOrder>
            {
                { index, sort }
            };
            RowComparer comp = new RowComparer()
            {
                SortColumns = sortColumns
            };
            var query = dt.AsEnumerable().OrderBy(q => q, comp);

            return(query.AsDataView().ToTable());
        }
Exemple #16
0
        /// <summary>
        /// Ctor takes the ListView to be sorted as a parameter.
        /// </summary>
        public ListViewSorter(ListView listView)
        {
            _listView              = listView;
            _listView.ColumnClick += new ColumnClickEventHandler(_listView_ColumnClick);

            CustomComparers = new Dictionary <ColumnHeader, RowComparer>();
            HandleClicks    = true;

            // This is the default comparer used if a custom comparer is not found.
            _defaultComparer = delegate(ListViewItem x, ListViewItem y)
            {
                return(string.Compare(x.SubItems[_col].Text, y.SubItems[_col].Text));
            };
        }
Exemple #17
0
        public void SortElement()
        {
            RowComparer    rComparer = new RowComparer();
            ColumnComparer cComparer = new ColumnComparer();

            foreach (List <Element> r in rows)
            {
                r.Sort(rComparer);
            }
            foreach (List <Element> c in columns)
            {
                c.Sort(cComparer);
            }
        }
        protected void UpdateSchema()
        {
            //Add fields to schema order by field type, then source index
            Schema.Fields =
                _fieldList.AsIndexed()
                .OrderBy(f => f.Value.FieldType == FieldType.Key ? 0 : f.Value.FieldType == FieldType.Fact ? 2 : 1)
                .ThenBy(f => f.Index)
                .Select(f => f.Value)
                .ToArray();



            Schema.CalculatedFields =
                FieldMappers.OfType <ICalculatedFieldContainer>().SelectMany(c => c.CalculatedFields).ToList();

            Iterator = new FieldMapperIterator(FieldMappers, Schema.Fields);

            _rowComparer = new RowComparer(Schema);

            RowMap = new Dictionary <object[], object[]>(_rowComparer);

            HashKey = _hashKeyField != null?Array.IndexOf(Schema.Fields, _hashKeyField) : (int?)null;

            if (HashKey.HasValue)
            {
                HashIndices = Schema.Keys.Concat(Schema.Dimensions).Where(fp => fp.Index != HashKey).Select(fp => fp.Index).ToArray();
            }

            _parentReferenceIndices.Clear();
            if (_parentReferences.Count > 0)
            {
                foreach (var field in Schema.Fields.AsIndexed())
                {
                    int parentIndex;
                    if (_parentReferences.TryGetValue(field.Value, out parentIndex))
                    {
                        _parentReferenceIndices.Add(new KeyValuePair <int, int>(parentIndex, field.Index));
                    }
                }
            }

            _emptyRow =
                Schema.Fields
                .Select(
                    f => f.DefaultValue ?? (f.ValueType.IsValueType ? Activator.CreateInstance(f.ValueType) : null))
                .ToArray();
        }
        public void TestSingle()
        {
            var schema = CreateSchema(
                new Field { ValueType = typeof(int), FieldType = FieldType.Key, });

            var row1 = new object[] { 1 };
            var row2 = new object[] { 1 };
            var row3 = new object[] { 3 };

            var comparer = new RowComparer(schema);
            Assert.IsTrue(comparer.Equals(row1, row2));
            Assert.IsFalse(comparer.Equals(row1, row3));

            Assert.IsTrue(comparer.Compare(row1, row2) == 0);
            Assert.IsTrue(comparer.Compare(row1, row3) == -1);
            Assert.IsTrue(comparer.Compare(row3, row2) == 1);
        }
        public void TestMulti()
        {
            var schema = CreateSchema(
                new Field {
                ValueType = typeof(string), FieldType = FieldType.Key
            },
                new Field {
                ValueType = typeof(int), FieldType = FieldType.Key
            },
                new Field {
                ValueType = typeof(DateTime?), FieldType = FieldType.Key
            },
                new Field {
                ValueType = typeof(int), FieldType = FieldType.Fact
            });

            var row1 = new object[] { "A", 1, null, 37 };
            var row2 = new object[] { "A", 1, null, 11 };
            var row3 = new object[] { "B", 1, null, 3 };
            var row4 = new object[] { "B", 1, new DateTime(2000, 1, 1), 9 };
            var row5 = new object[] { "B", 1, new DateTime(2000, 1, 1), 11 };
            var row6 = new object[] { "B", 1, new DateTime(2000, 1, 2), 3 };
            var row7 = new object[] { "B", 2, new DateTime(2000, 1, 2), 2 };
            var row8 = new object[] { "C", 19, new DateTime(2000, 1, 2), 2 };

            var comparer = new RowComparer(schema);

            Assert.IsTrue(comparer.Equals(row1, row2));
            Assert.IsFalse(comparer.Equals(row1, row4));
            Assert.IsTrue(comparer.Equals(row4, row5));
            Assert.IsFalse(comparer.Equals(row3, row4));

            Assert.IsTrue(comparer.Compare(row1, row2) == 0);
            Assert.IsTrue(comparer.Compare(row1, row3) == -1);
            Assert.IsTrue(comparer.Compare(row3, row2) == 1);
            Assert.IsTrue(comparer.Compare(row4, row3) == 1);
            Assert.IsTrue(comparer.Compare(row3, row4) == -1);
            Assert.IsTrue(comparer.Compare(row4, row5) == 0);
            Assert.IsTrue(comparer.Compare(row5, row6) == -1);
            Assert.IsTrue(comparer.Compare(row6, row7) == -1);
            Assert.IsTrue(comparer.Compare(row7, row8) == -1);
        }
        public void TestSingle()
        {
            var schema = CreateSchema(
                new Field {
                ValueType = typeof(int), FieldType = FieldType.Key,
            });

            var row1 = new object[] { 1 };
            var row2 = new object[] { 1 };
            var row3 = new object[] { 3 };

            var comparer = new RowComparer(schema);

            Assert.IsTrue(comparer.Equals(row1, row2));
            Assert.IsFalse(comparer.Equals(row1, row3));

            Assert.IsTrue(comparer.Compare(row1, row2) == 0);
            Assert.IsTrue(comparer.Compare(row1, row3) == -1);
            Assert.IsTrue(comparer.Compare(row3, row2) == 1);
        }
Exemple #22
0
        private void SortInput()
        {
            _spooledRowsList = new List <object[]>();

            while (Input.Read())
            {
                object[] rowValues = new object[Input.RowBuffer.Length];
                Input.RowBuffer.CopyTo(rowValues, 0);
                _spooledRowsList.Add(rowValues);
            }

            int[] sortedColumnIndexes = new int[SortEntries.Length];
            for (int i = 0; i < sortedColumnIndexes.Length; i++)
            {
                sortedColumnIndexes[i] = SortEntries[i].SourceIndex;
            }

            RowComparer rowComparer = new RowComparer(SortEntries, SortOrders, Comparers);

            _spooledRowsList.Sort(rowComparer);
        }
        public List <Row> RecursiveSimplification()
        {
            OrderTheRows(_nonSimplifiedTruthTable);

            var lastStep0 = _simplificationStepsForZeros[_simplificationStepsForZeros.Count - 1];
            var lastStep1 = _simplificationStepsForOnes[_simplificationStepsForOnes.Count - 1];

            for (int i = 0; i < _numberOfVariables; i++)
            {
                Simplify(lastStep0, _simplificationStepsForZeros);
                Simplify(lastStep1, _simplificationStepsForOnes);
                lastStep0 = _simplificationStepsForZeros[_simplificationStepsForZeros.Count - 1];
                lastStep1 = _simplificationStepsForOnes[_simplificationStepsForOnes.Count - 1];
            }

            var rowComparer = new RowComparer();
            var trueValues  = lastStep1.SelectMany(x => x).Distinct(rowComparer);
            var falseValues = lastStep0.SelectMany(x => x).Distinct(rowComparer);

            return(falseValues.Concat(trueValues).ToList());
        }
Exemple #24
0
        public IEnumerator <SqlDataRecord> GetEnumerator()
        {
            var sortIndices = Enumerable.Repeat(-1, _data.Schema.Fields.Length).ToArray();
            var ix          = 0;

            foreach (var field in RowComparer.GetSortFields(_data.Schema))
            {
                sortIndices[field.Index] = ix++;
            }


            var metadata = _data.Schema.Fields.Select((f, i) =>
            {
                var t = _types[f.ValueType];

                var sortOrder = sortIndices[i] != -1
                    ? (f.SortOrder == SortOrder.Descending
                        ? System.Data.SqlClient.SortOrder.Descending
                        : System.Data.SqlClient.SortOrder.Ascending)
                    : System.Data.SqlClient.SortOrder.Unspecified;

                if (t == SqlDbType.NVarChar || t == SqlDbType.VarChar || t == SqlDbType.VarBinary)
                {
                    return(new SqlMetaData(f.Name, t, SqlMetaData.Max, false, _data.Schema.IsKey(f), sortOrder, sortIndices[i]));
                }

                return(new SqlMetaData(f.Name, t, false, _data.Schema.IsKey(f), sortOrder, sortIndices[i]));
            }).ToArray();

            var record = new SqlDataRecord(metadata);

            foreach (var row in _data.Rows)
            {
                for (var i = 0; i < row.Length; i++)
                {
                    record.SetValue(i, row[i]);
                }
                yield return(record);
            }
        }
            internal static GtkListView <string> Build()
            {
                var comparer = new RowComparer();
                var renderer = new ColumnRenderer();
                var columns  = new List <TreeViewColumn>();

                columns.Add(
                    TreeBuilder.CreateColumn(
                        "Text", // TODO move constant elsewhere
                        250,    // TODO move constant elsewhere
                        renderer.RenderText));

                var result = new GtkListView <string>(
                    columns,
                    new Dictionary <int, TreeIterCompareFunc>()
                {
                    { (int)Columns.Text, comparer.Compare }
                },
                    null);

                return(result);
            }
Exemple #26
0
        public override void Render(Report report, Flow fm, DataContext dataContext)
        {
            HashSet <String> fieldNames = new HashSet <string>();

            foreach (var c in Columns)
            {
                if (c.DataField != "#")
                {
                    fieldNames.Add(c.DataField);
                }
                if (c.AggregateWeightDataField != null)
                {
                    fieldNames.Add(c.AggregateWeightDataField);
                }
            }

            foreach (var g in Groups)
            {
                foreach (var sc in g.GroupByColumns)
                {
                    fieldNames.Add(sc.DataField);
                }
            }

            var data = dataContext.CreateTable(DataTable, fieldNames.ToArray());


            for (int i = 0; i < Columns.Length; i++)
            {
                Columns[i]._Index          = i;
                Columns[i]._DataFieldIndex = data.GetColumnIndex(Columns[i].DataField);

                if (Columns[i].AggregateWeightDataField != null)
                {
                    Columns[i]._AggregateWeightDataFieldIndex = data.GetColumnIndex(Columns[i].AggregateWeightDataField);
                    if (Columns[i]._AggregateWeightDataFieldIndex == -1)
                    {
                        throw new InvalidOperationException(String.Format("Weight column '{0}' not found.", Columns[i].AggregateWeightDataField));
                    }
                }
            }



            List <SortColumn> sort      = new List <SortColumn>();
            List <GroupData>  groupData = new List <GroupData>();

            int gi = 0;

            if (Groups != null)
            {
                foreach (var g in Groups)
                {
                    var gd = new GroupData();
                    var gc = new List <SortColumn>();
                    if (g.GroupByColumns != null)
                    {
                        foreach (var c in g.GroupByColumns)
                        {
                            var ci = data.GetColumnIndex(c.DataField);
                            if (ci != -1)
                            {
                                gc.Add(new SortColumn
                                {
                                    ColumnIndex   = ci,
                                    SortDirection = c.SortDirection == SortDirection.None ? SortDirection.Ascending : c.SortDirection
                                });
                            }
                        }
                    }
                    gd.Columns = gc.ToArray();
                    sort.AddRange(gd.Columns);
                    gd.GroupIndex = gi++;
                    gd.Group      = g;

                    if (g.CaptionFormat != null)
                    {
                        String[] names;
                        String   format;
                        StringFormatHelper.PrepareFormatWithNames(g.CaptionFormat, out format, out names);

                        gd.PreparedCaptionFormat  = format;
                        gd.PreparedCaptionColumns = names != null?names.Select(a => data.GetColumnIndex(a)).ToArray() : null;
                    }

                    if (g.FooterFormat != null)
                    {
                        String[] names;
                        String   format;
                        StringFormatHelper.PrepareFormatWithNames(g.FooterFormat, out format, out names);

                        gd.PreparedFooterFormat  = format;
                        gd.PreparedFooterColumns = names != null?names.Select(a => data.GetColumnIndex(a)).ToArray() : null;
                    }

                    gd.GroupLevel = Groups.Length - gd.GroupIndex - 1;
                    gd.GroupOpen  = false;
                    groupData.Add(gd);
                }
            }

            sort.AddRange(from c in Columns
                          where c.SortDirection != SortDirection.None
                          orderby c.SortIndex
                          select new SortColumn
            {
                ColumnIndex   = c._DataFieldIndex,
                SortDirection = c.SortDirection
            });

            if (sort.Count != 0)
            {
                data.Sort(sort.ToArray());
            }

            var rows = data.Rows;
            var rect = fm.GetRect(Position, Columns.Length, 0);
            var pos  = new RowCol {
                Col = rect.Col1, Row = rect.Row1
            };
            var         startRow = pos.Row;
            List <Cell> cells    = new List <Cell>();


            object[]        accumulator = new object[Columns.Length];
            decimal[]       count       = new decimal[Columns.Length];
            CellAlignment[] align       = new CellAlignment[Columns.Length];

            for (int c = 0; c < Columns.Length; c++)
            {
                var th = Columns[c]._DataFieldIndex >= 0 ? data.TypeHelper[Columns[c]._DataFieldIndex] : null;
                if (th != null)
                {
                    switch (Columns[c].AggregateFunction)
                    {
                    case AggregateFunction.Sum:
                        accumulator[c] = th.Math.Zero;
                        break;

                    case AggregateFunction.Count:
                        accumulator[c] = 0;
                        break;

                    case AggregateFunction.Avg:
                        if (Columns[c].AggregateWeightDataField != null)
                        {
                            count[c]       = 0;
                            accumulator[c] = 0m;
                        }
                        else
                        {
                            accumulator[c] = th.Math.Zero;
                            count[c]       = 0;
                        }
                        break;

                    case AggregateFunction.Product:
                        accumulator[c] = th.Math.One;
                        break;
                    }
                }
                align[c] = th != null?CalcAlignment(Columns[c].CellAlignment, th) : CellAlignment.Right;
            }

            Data.Row prevRow = null;
            for (int r = 0, rowIndex = 0; r <= rows.Length; r++, rowIndex++)
            {
                var row = r < rows.Length ? rows[r] : null;
                var closeToGroupLevel = row != null ? groupData.Count : 0;

                if (prevRow != null && row != null)
                {
                    for (int g = 0; g < groupData.Count; g++)
                    {
                        if (RowComparer.Compare(row, prevRow, groupData[g].Columns) != 0)
                        {
                            closeToGroupLevel = g;
                            break;
                        }
                    }
                }

                //close higher groups first
                for (int g = groupData.Count - 1; g >= closeToGroupLevel; g--)
                {
                    var gd = groupData[g];
                    if (gd.GroupOpen)
                    {
                        gd.GroupOpen = false;
                        //close group
                        if (gd.Group.ShowFooter)
                        {
                            for (int c = 0; c < Columns.Length; c++)
                            {
                                if (Columns[c].AggregateFunction == AggregateFunction.Avg)
                                {
                                    gd.GroupAccumulator[c] = CalculateAggregate(Columns[c].AggregateFunction, gd.GroupAccumulator[c], gd.GroupCounter[c]);
                                }

                                var style = gd.GetFooterCellStyle(Columns[c].ColumnType);
                                switch (Columns[c].FooterType)
                                {
                                case ColumnFooterType.FooterText:
                                    cells.Add(new Cell {
                                        Column = pos.Col + c, Row = pos.Row, FormattedValue = Columns[c].FooterText, Value = Columns[c].FooterText, CellStyleIndex = style, Alignment = Columns[c].FooterAlignment
                                    });
                                    break;

                                case ColumnFooterType.AggregateValue:
                                    String fv = (Columns[c].FooterFormat != null) ? String.Format(Columns[c].FooterFormat, gd.GroupAccumulator[c]) : (gd.GroupAccumulator[c] != null ? gd.GroupAccumulator[c].ToString() : null);
                                    var    al = Columns[c]._DataFieldIndex >= 0 ? CalcAlignment(Columns[c].FooterAlignment, data.TypeHelper[Columns[c]._DataFieldIndex]) : CellAlignment.Auto;
                                    cells.Add(new Cell {
                                        Column = pos.Col + c, Row = pos.Row, FormattedValue = fv, Value = gd.GroupAccumulator[c], CellStyleIndex = style, Alignment = al, Format = Columns[c].FooterFormat
                                    });
                                    break;

                                case ColumnFooterType.GroupFooter:
                                    String gfv = gd.PreparedFooterColumns == null ? gd.PreparedFooterFormat : String.Format(gd.PreparedFooterFormat, prevRow.GetMany(gd.PreparedFooterColumns));
                                    var    gal = Columns[c]._DataFieldIndex >= 0 ? CalcAlignment(Columns[c].FooterAlignment, data.TypeHelper[Columns[c]._DataFieldIndex]) : CellAlignment.Auto;
                                    cells.Add(new Cell {
                                        Column = pos.Col + c, Row = pos.Row, FormattedValue = gfv, Value = gfv, CellStyleIndex = style, Alignment = gal
                                    });
                                    break;
                                }
                                if (Columns[c].FooterColSpan > 1)
                                {
                                    report.MergedCells.Add(new Rect {
                                        Col1 = pos.Col + c, Col2 = pos.Col + c + Columns[c].FooterColSpan - 1, Row1 = pos.Row, Row2 = pos.Row
                                    });
                                    c += Columns[c].FooterColSpan - 1;
                                }
                            }
                            pos.Row++;
                        }
                    }
                }

                for (int g = 0; g < groupData.Count; g++)
                {
                    var gd = groupData[g];
                    //add row
                    if (row != null)
                    {
                        if (!gd.GroupOpen)
                        {
                            gd.GroupOpen = true;
                            rowIndex     = 0;

                            if (gd.Group.ShowCaption)
                            {
                                String caption = gd.PreparedCaptionColumns == null ? gd.PreparedCaptionFormat : String.Format(gd.PreparedCaptionFormat, row.GetMany(gd.PreparedCaptionColumns));

                                cells.Add(new Cell {
                                    Column = pos.Col, Row = pos.Row, FormattedValue = caption, Value = caption, CellStyleIndex = gd.GetCaptionStyle()
                                });
                                report.MergedCells.Add(new Rect {
                                    Col1 = pos.Col, Col2 = pos.Col + Columns.Length - 1, Row1 = pos.Row, Row2 = pos.Row
                                });
                                pos.Row++;
                            }

                            if (gd.Group.ShowHeader)
                            {
                                for (int c = 0; c < Columns.Length; c++)
                                {
                                    var ht    = Columns[c].HeaderText;
                                    var style = gd.GetHeaderCellStyle(Columns[c].ColumnType);
                                    var a     = Columns[c]._DataFieldIndex >= 0 ? CalcAlignment(Columns[c].HeaderAlignment, data.TypeHelper[Columns[c]._DataFieldIndex]) : CellAlignment.Right;

                                    cells.Add(new Cell
                                    {
                                        Column         = pos.Col + c,
                                        Row            = pos.Row,
                                        FormattedValue = ht,
                                        Value          = ht,
                                        CellStyleIndex = style,
                                        Alignment      = a
                                    });
                                }
                                pos.Row++;
                            }

                            gd.GroupAccumulator = new object[Columns.Length];
                            gd.GroupCounter     = new decimal[Columns.Length];

                            //reset group accumulator
                            for (int c = 0; c < Columns.Length; c++)
                            {
                                var th = Columns[c]._DataFieldIndex >= 0 ? data.TypeHelper[Columns[c]._DataFieldIndex] : null;
                                if (th != null)
                                {
                                    switch (Columns[c].AggregateFunction)
                                    {
                                    case AggregateFunction.Sum:
                                        gd.GroupAccumulator[c] = th.Math.Zero;
                                        break;

                                    case AggregateFunction.Count:
                                        gd.GroupAccumulator[c] = 0;
                                        break;

                                    case AggregateFunction.Avg:
                                        if (Columns[c].AggregateWeightDataField != null)
                                        {
                                            gd.GroupAccumulator[c] = 0m;
                                            gd.GroupCounter[c]     = 0;
                                        }
                                        else
                                        {
                                            gd.GroupAccumulator[c] = th.Math.Zero;
                                            gd.GroupCounter[c]     = 0;
                                        }
                                        break;

                                    case AggregateFunction.Product:
                                        gd.GroupAccumulator[c] = th.Math.One;
                                        break;
                                    }
                                }
                            }
                        }

                        for (int c = 0; c < Columns.Length; c++)
                        {
                            var dfi = Columns[c]._DataFieldIndex;
                            var v   = row[dfi];

                            var th = dfi >= 0 ? data.TypeHelper[dfi] : null;
                            if (th != null)
                            {
                                switch (Columns[c].AggregateFunction)
                                {
                                case AggregateFunction.Sum:
                                    gd.GroupAccumulator[c] = th.Math.SumNullAsZero(gd.GroupAccumulator[c], v);
                                    break;

                                case AggregateFunction.Count:
                                    if (v != null)
                                    {
                                        gd.GroupAccumulator[c] = (int)gd.GroupAccumulator[c] + 1;
                                    }
                                    break;

                                case AggregateFunction.Product:
                                    gd.GroupAccumulator[c] = th.Math.Multiply(gd.GroupAccumulator[c], v);
                                    break;

                                case AggregateFunction.Avg:
                                    if (v != null)
                                    {
                                        if (Columns[c].AggregateWeightDataField != null)
                                        {
                                            var w = row[Columns[c]._AggregateWeightDataFieldIndex];
                                            if (w != null)
                                            {
                                                var wd = Convert.ToDecimal(w);
                                                var wv = wd * Convert.ToDecimal(v);
                                                gd.GroupAccumulator[c] = (decimal)gd.GroupAccumulator[c] + wv;
                                                gd.GroupCounter[c]    += wd;
                                            }
                                        }
                                        else
                                        {
                                            gd.GroupAccumulator[c] = th.Math.Sum(gd.GroupAccumulator[c], v);
                                            ++gd.GroupCounter[c];
                                        }
                                    }
                                    break;

                                case AggregateFunction.Min:
                                    if (gd.GroupAccumulator[c] == null)
                                    {
                                        gd.GroupAccumulator[c] = v;
                                    }
                                    else if (v != null)
                                    {
                                        gd.GroupAccumulator[c] = th.Math.Min(gd.GroupAccumulator[c], v);
                                    }
                                    break;

                                case AggregateFunction.Max:
                                    if (gd.GroupAccumulator[c] == null)
                                    {
                                        gd.GroupAccumulator[c] = v;
                                    }
                                    else if (v != null)
                                    {
                                        gd.GroupAccumulator[c] = th.Math.Max(gd.GroupAccumulator[c], v);
                                    }
                                    break;
                                }
                            }

                            switch (Columns[c].CellDisplayMode)
                            {
                            default:
                            case CellDisplayMode.Normal:
                                v = Columns[c].DataField == "#" ? rowIndex + 1 : row[dfi];
                                break;

                            case CellDisplayMode.RowNumber:
                                v = rowIndex + 1;
                                break;

                            case CellDisplayMode.AccumulatorValue:
                                v = CalculateAggregate(Columns[c].AggregateFunction, gd.GroupAccumulator[c], gd.GroupCounter[c]);
                                break;
                            }

                            CellStyle addStyle = null;
                            if (Columns[c].ConditionalFormatting != null)
                            {
                                addStyle = Columns[c].ConditionalFormatting(v);
                            }

                            String fv = (Columns[c].Format != null) ? String.Format(Columns[c].Format, v) : (v != null ? v.ToString() : null);

                            if (g + 1 == groupData.Count)
                            {
                                cells.Add(new Cell
                                {
                                    Column         = pos.Col + c,
                                    Row            = pos.Row,
                                    Value          = v,
                                    FormattedValue = fv,
                                    CellStyleIndex = Columns[c].ColumnType == TableColumnType.HeaderColumn ? CellStyleIndex.TableRowHeader : Columns[c].ColumnType == TableColumnType.FooterColumn ? CellStyleIndex.TableRowFooter : CellStyleIndex.TableRow,
                                    Alignment      = align[c],
                                    Format         = Columns[c].Format,
                                    CustomStyle    = addStyle
                                });
                            }
                        }

                        if (g + 1 == groupData.Count)
                        {
                            pos.Row++;
                        }
                    }
                }

                prevRow = row;
            }

            fm.GetRect(RowCol.Zero, 0, pos.Row - startRow);

            report.Cells.AddRange(cells);
        }
Exemple #27
0
        private void Dgv_Patient_Sorted(object sender, EventArgs e)
        {
            if (Dgv_Patient != null && lieMing == "床号")
            {
                #region 第一版排序
                ListSortDirection           direction   = new ListSortDirection();
                DataTable                   dt          = dvtodt(Dgv_Patient);
                Dictionary <int, SortOrder> sortColumns =
                    new Dictionary <int, SortOrder>();
                if (m == 0)
                {
                    RowComparer comp = new RowComparer(SortOrder.Ascending);
                    sortColumns.Add(1, SortOrder.Ascending);
                    direction = ListSortDirection.Ascending;
                    m         = 1;

                    comp.SortColumns = sortColumns;
                    var query3 = dt.AsEnumerable().OrderBy(q => q, comp);
                    //DataView dv3 = query3.AsDataView();
                    DataTable dv3 = query3.CopyToDataTable();
                    Dgv_Patient.Rows.Clear();
                    for (int i = 0; i < dv3.Rows.Count; i++)
                    {
                        Dgv_Patient.Rows.Add(1);
                        Dgv_Patient.Rows[i].Cells["dgv_PatName"].Value      = dv3.Rows[i]["Column2"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_BedNo"].Value        = dv3.Rows[i]["Column3"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_PatCode"].Value      = dv3.Rows[i]["Column4"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_UnCheckCount"].Value = dv3.Rows[i]["Column5"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_TotalCount"].Value   = dv3.Rows[i]["Column6"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_BatchSaved"].Value   = dv3.Rows[i]["Column7"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_IsSame"].Value       = dv3.Rows[i]["Column8"].ToString();
                        Dgv_Patient.Rows[i].Cells["IsOpen"].Value           = dv3.Rows[i]["Column9"].ToString();
                        Dgv_Patient.Rows[i].Cells["WardCode"].Value         = dv3.Rows[i]["Column10"].ToString();
                    }
                    //Dgv_Patient.DataSource = dv3;
                }
                else
                {
                    RowComparer comp = new RowComparer(SortOrder.Descending);
                    sortColumns.Add(1, SortOrder.Descending);
                    direction = ListSortDirection.Descending;
                    m         = 0;

                    comp.SortColumns = sortColumns;
                    var       query3 = dt.AsEnumerable().OrderBy(q => q, comp);
                    DataTable dv3    = query3.CopyToDataTable();
                    Dgv_Patient.Rows.Clear();
                    for (int i = 0; i < dv3.Rows.Count; i++)
                    {
                        Dgv_Patient.Rows.Add(1);
                        Dgv_Patient.Rows[i].Cells["dgv_PatName"].Value      = dv3.Rows[i]["Column2"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_BedNo"].Value        = dv3.Rows[i]["Column3"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_PatCode"].Value      = dv3.Rows[i]["Column4"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_UnCheckCount"].Value = dv3.Rows[i]["Column5"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_TotalCount"].Value   = dv3.Rows[i]["Column6"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_BatchSaved"].Value   = dv3.Rows[i]["Column7"].ToString();
                        Dgv_Patient.Rows[i].Cells["dgv_IsSame"].Value       = dv3.Rows[i]["Column8"].ToString();
                        Dgv_Patient.Rows[i].Cells["IsOpen"].Value           = dv3.Rows[i]["Column9"].ToString();
                        Dgv_Patient.Rows[i].Cells["WardCode"].Value         = dv3.Rows[i]["Column10"].ToString();
                    }
                    //Dgv_Patient.DataSource = dv3;
                }
                Dgv_Patient.Columns["dgv_BedNo"].HeaderCell.SortGlyphDirection = direction == ListSortDirection.Ascending ? SortOrder.Ascending : SortOrder.Descending;
                #endregion

                //#region 第二版排序
                //DataTable dt = dvtodt(Dgv_Patient);
                //DataTable dt1 = dt.Copy();
                //DataTable dt2 = dt.Copy();
                //DataTable dt3 = dt.Copy();
                //DataTable dt4 = dt.Copy();
                //dt1.Clear();
                //dt2.Clear();
                //dt3.Clear();
                //dt4.Clear();
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                //    if (dt.Rows[i]["Columns3"].ToString().Substring(0, 1) == "+")
                //    {
                //        dt1.Rows.Add(dt.Rows[i]);

                //    }
                //    else if (dt.Rows[i]["Columns3"].ToString().Substring(dt.Rows[i]["Columns3"].ToString().Length - 1, 1) == "+")
                //    {
                //        dt2.Rows.Add(dt.Rows[i]);

                //    }
                //    else if (IsNumeric(dt.Rows[i]["Columns3"].ToString()))
                //    {
                //        dt3.Rows.Add(dt.Rows[i]);
                //    }
                //    else
                //    {
                //        dt4.Rows.Add(dt.Rows[i]);
                //    }

                //}


                //#endregion
            }
        }
 internal void Sort(IComparer customComparer, bool ascending)
 {
     if (this.items.Count > 0)
     {
         RowComparer rowComparer = new RowComparer(this, customComparer, ascending);
         this.items.CustomSort(rowComparer);
         // Caller takes care of the dataGridView invalidation
     }
 }
 internal void Sort(IComparer customComparer, bool ascending)
 {
     if (this.items.Count > 0)
     {
         RowComparer rowComparer = new RowComparer(this, customComparer, ascending);
         this.items.CustomSort(rowComparer);
     }
 }
            public void CustomSort(RowComparer rowComparer)
            {
                Debug.Assert(rowComparer != null);
                Debug.Assert(this.Count > 0);

                this.rowComparer = rowComparer;
                CustomQuickSort(0, this.Count - 1);
            }
        public void TestDimensionKey()
        {
            var schema = CreateSchema(
                new Field { ValueType = typeof(int), FieldType = FieldType.Dimension, },
                new Field { ValueType = typeof(int), FieldType = FieldType.Dimension, },
                new Field { ValueType = typeof(int), FieldType = FieldType.Fact, });

            var row1 = new object[] { 1, 1, 1 };
            var row2 = new object[] { 1, 1, 4 };
            var row3 = new object[] { 1, 2, 1 };

            var comparer = new RowComparer(schema);
            Assert.IsTrue(comparer.Equals(row1, row2));
            Assert.IsFalse(comparer.Equals(row1, row3));

            Assert.IsTrue(comparer.Compare(row1, row2) == 0);
            Assert.IsTrue(comparer.Compare(row1, row3) == -1);
            Assert.IsTrue(comparer.Compare(row3, row2) == 1);
        }
Exemple #32
0
 public SorterContext(Resultset source, RowComparer comparer)
     : base(new Resultset[] { source })
 {
     _source = source;
     _comparer = comparer;
 }
        protected void UpdateSchema()
        {
            //Add fields to schema order by field type, then source index
            Schema.Fields =
                _fieldList.AsIndexed()
                .OrderBy(f => f.Value.FieldType == FieldType.Key ? 0 : f.Value.FieldType == FieldType.Fact ? 2 : 1)
                    .ThenBy(f => f.Index)
                    .Select(f => f.Value)
                    .ToArray();



            Schema.CalculatedFields =
                FieldMappers.OfType<ICalculatedFieldContainer>().SelectMany(c => c.CalculatedFields).ToList();

            Iterator = new FieldMapperIterator(FieldMappers, Schema.Fields);

            _rowComparer = new RowComparer(Schema);

            RowMap = new Dictionary<object[], object[]>(_rowComparer);
            
            HashKey = _hashKeyField != null ? Array.IndexOf(Schema.Fields, _hashKeyField) : (int?) null;

            if (HashKey.HasValue)
            {
                HashIndices = Schema.Keys.Concat(Schema.Dimensions).Where(fp=>fp.Index != HashKey).Select(fp => fp.Index).ToArray();
            }

            _parentReferenceIndices.Clear();
            if (_parentReferences.Count > 0)
            {
                foreach (var field in Schema.Fields.AsIndexed())
                {
                    int parentIndex;
                    if (_parentReferences.TryGetValue(field.Value, out parentIndex))
                    {
                        _parentReferenceIndices.Add(new KeyValuePair<int, int>(parentIndex, field.Index));
                    }
                }
            }

            _emptyRow =
                Schema.Fields
                    .Select(
                        f => f.DefaultValue ?? (f.ValueType.IsValueType ? Activator.CreateInstance(f.ValueType) : null))
                    .ToArray();
        }