When I add rows to a Datatable, and later iterate that Datatable.
Will I get the rows in the same order then they were inserted? First in, first out?
Or can I not rely on that order?
row = datatable.NewRow();
row("id") = 1;
table.Rows.Add(row);
row = datatable.NewRow();
row("id") = 2;
table.Rows.Add(row);
foreach(Row row in datatable.AsEnumerable())
{
// FIFO here? always get row with id 1 as first row and row with id 2 as second row?
}
If you do this manually, YES of course.
MSDN - Adding Data to a DataTable
Note that values in the array are matched sequentially to the columns,
based on the order in which they appear in the table.
Yes, normally that is what should happen.
If you need an explicit ordering of the rows I would suggest you sort them before iterating through them. Either by doing an OrderBy<> linq type query or by using the Select method on the DataTable.
Also, you can use the Rows property of the DataTable to get an enumerable of all rows instead of doing the AsEnumerable call.
Edit:
By inspecting the decompiled sources for the DataTable I found that the Rows property of the DataTable returns a DataRowCollection object. The DataRowCollection stores the rows in a binary tree based structure that allows you to fetch the items based on its array index. So it will return the rows in the same order as they were added. As long as we expose an indexer that takes a numerical index this is implied.
In addition, the AsEnumerable extension method, will turn the Rows into an EnumerableRowsCollection that wraps the same types as an IEnumerable<DataRow>.
Related
I have data being processed by an app which needs to sort the data based on whether or not a bit is flipped. The tables are identical. The code as it stands looks something like this:
DataTable dt2 = dt1.Clone();
DataRow r = dt1.NewRow();
FillUp(ref r);
if(bitISetEarlier)
dt2.ImportRow(r);
else
dt1.ImportRow(r);
Now, a clear problem I was having is that if the row wasn't already attached to a table, ImportRow() fails silently and I end up with an empty table. When I changed this to:
if(bitISetEarlier)
dt2.Rows.Add(r);
else
dt1.Rows.Add(r);
I started getting an exception saying that a function was trying to add a row that existed for another table. So when I tried this:
if(bitISetEarlier)
if(r.RowState == DataRowState.Detached)
dt2.Rows.Add(r)
else dt2.ImportRow(r);
else
if(r.RowState == DataRowState.Detached)
dt1.Rows.Add(r)
else dt1.ImportRow(r);
the exception stopped, but any attempt to assign to dt2 still states that the row belongs to another table, but if I comment out the dt2 if statement and just attempt ImportRow(), the dt2.Rows.Count remains at 0 and no records assigned.
I need to populate the DataRow before knowing which table it belongs in, but I have no idea what columns the row will have before it hits this function. The condition that indicates which table it should go to is not stored with the data in the DataTable.
Is the problem that even though they have identical columns, NewRow() is adding an attribute to the row that makes it incompatible with the sister table? Is there a way I can get the same functionality as NewRow() (copy schema without knowing what any of the columns are ahead of time) but that I can dynamically assign? I'm aware I could probably manually construct a row that is compatible with either by wrapping it in a for loop and building out the columns every time i need the new row using the DataTable.Columns property, but I'd like to avoid doing that if possible.
I found my solution. Since I can't add the row built off of one table to the other table directly, I figured it was the DataRow object that was problematic, but the ItemArray property was probably all I needed.
if (isErrorRow)
{
//nr is the NewRow for dt1
var nr2 = dt2.NewRow();
nr2.ItemArray = nr.ItemArray;
dt2.Rows.Add(nr2);
}
This effectively cloned the rows.
I need to compare two datatable and simply check if Datatable(A) contains rows which are in Datatable(B).
Then rows from (B) which will not be in (A) will be inserted into (A). So basically target is to insert rows from (B) into (A) but only those rows which are not already presented.
Both Datables have same structure, same columns and datatypes.
I donĀ“t want to do it with foreach loop for every Datarow(B) and compare with every Datarow in (A) it will be very slow solutions.
Thank you in advance
I'm fairly new to C# programming. I want to take user input from DataGridView to a DataTable. However, I get ArgumentException from this code
DataTable dd=new DataTable();
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
dd.Rows.Add(dr);
}
Is there any way I can do to fix it? I'd like to have alternatives to get input from dataGridView1 as well.
edit: forgot to mention, dataGridView1 has one comboBox column.
edit2: the error read "Input array is longer than the number of columns in this table."
Input array is longer than the number of columns in this table.
You have to add a column to DataTable eg: dd.Columns.Add("SomeColumnName"), before you add rows to it.
However, if there's no particular requirement to use DataTable then you should use, for example, List to store the rows. It is a much simpler data structure.
var listOfRows = gridView.Rows.Cast<DataGridViewRow>().ToList();
I'm using a SqlDataReader to add row by row into a datatable like follows:
while (reader.Read())
{
dataTable.LoadDataRow(reader.CurrentRow(), LoadOption.PreserveChanges);
}
This works, but I need to be able to avoid adding duplicate rows to the dataTable. I would love to be able to use the Contains or Find methods from the dataTable, but I can't find a way to turn the object[] from reader.CurrentRow() into a DataRow to compare to without adding it to a datatable.
I've looked into the option of making a hashset of the object[]s, and then adding them all at once to the datatable at the end, but I forgot that the default object IEqualityComparer only compares the reference.
Is there a feasible way of doing this without removing the duplicates at the end?
If removing the duplicates is the only way to go, what is the best way to do that?
EDIT:
I'm splitting distinct rows from the database into separate datatables in code. Each row from the query result is distinct, but sections of each row are not. Unfortunately I need to do exactly what my question is asking, as the results from the query are already distinct.
You didn't provide a ton of detail, but I hope this is comprehensive.
If you need a single column to be unique, then in your Columns collection in your datatable, specify the column like this:
DataTable appeals = new DataTable("Appeals");
appeals.Columns["PriorAppealNumber"].Unique = true;
DataColumn keyField = new DataColumn("AppealNumber", typeof(string));
appeals.Columns.Add(keyField);
If the uniqueness needs to span multiple rows, this is the method:
var myUniqueConstraint = new UniqueConstraint( new DataColumn[] {appeals.Columns[0], appeals.Columns[1], appeals.Columns[2]} );
appeals.Constraints.Add(myUniqueConstraint);
That will enforce the constraints BEFORE you try to commit back to the source database.
The easiest way is to actually make sure there are no duplicate rows at all - if you're querying relational database use DISTINCT - that will return only unique rows.
Am using foreach loop that contain some code to retraive data from database. first time it returns some rows from database.In second looping it returns some rows so and so. My question is may i merge the looping rows to single dataset?.
please help me to merge that row values to single dataset....
As #Tim Schmelter mentioned there is also the Merge() method on datasets. This will allow you to different types of merges, including updates which will stop you having duplicate rows if you have the same row in each dataset. This maybe better than using a for loop to add the rows from one to the other depending on the type of data you have.
you can read more on this here:
http://msdn.microsoft.com/en-us/library/803bh6bc.aspx
This is provided I understood you correctly ...
DataTable tbl = new DataTable();
foreach (DataRow row in data.Rows)
{
tbl.Rows.Add(row);
}
Then just add the DataTable to a DataSet of your choice.