check if a value exists in DataRow array - c#

In my application i am filtering a datatable using a filter expression and am getting a DataRow which matches the condition.Now i want to check if the value of particular column exists in any row of DataRow array.
Code:
string FilterCond1 = "id=" + getId;
DataRow[] myrow = DataTable.Select(FilterCond1);
if (myrow.Length > 0)
{
//check for size=28 in DataRow[]
}
else
{
}
I have column size in the datatable DataTable and i want to check if any row of the DataRow array has a value 28 in the column size.How can i go about it?

Try this
string FilterCond1 = "id=" + getId;
DataRow[] myrow = DataTable.Select(FilterCond1);
if (myrow.Length > 0)
{
for(int i = 0; i < myrow.Length; i ++)
{
if(myrow[i]["size"].ToString() == "28")
{
// YOUR CODE HERE
}
}
}
else
{
}
EDIT
Just add the condition to your filter.
string FilterCond1 = "id=" + getId + " AND size=28";
Then you don't need the if(myrow[i]["size"].ToString() == "28") as you know the rows in the array are the one you want.

You can use column collection to access particular column value within row.
if(myrow[rowIndex]["ColoumnName"].ToString() == "somevalue")
Where row index could from zero to length-1
Edit based on comments, you can put multiple condition on column in select, check it here, and may not need to iterate.
string FilterCond1 = "id=" + getId + " AND size = " + 28;
DataRow[] myrow = dt.Select(FilterCond1);
To iterate through rows collection
for(int i=0; i < myrow.Length; i++)
{
if(myrow[i]["size"].ToString() == "28")
{
//your code
}
}

First you should aiterate through all rows using foreach then use the below code..
if(myrow[row]["size"] == 28)
or
int ColIndex = 3; // replace 3 with ur co. index
if(myrow[row][ColIndex] == 28)

Related

print an entire table in C#

I'm trying to print the content of a DataTable, starting with the column headers, followed by the content of the table tupples.
output.Add($"Table : [{dataTable.TableName}]");
string strColumnNames = "";
foreach (DataColumn col in dataTable.Columns)
{
if (strColumnNames == "")
strColumnNames = col.ColumnName.PadLeft(col.MaxLength - col.ColumnName.Length); // (*)
else strColumnNames = strColumnNames + "|" +
col.ColumnName.PadLeft(col.MaxLength - col.ColumnName.Length); // (*)
}
output.Add($"[{strColumnNames}]");
foreach (DataRow dataRow in dataTable.Rows)
{
string temp = "";
for (int i = 0; i < dataRow.ItemArray.Count(); i++)
{
if (i == 0)
temp = dataRow.ItemArray[i].ToString(); // (**)
else temp += "|" + dataRow.ItemArray[i].ToString(); // (**)
}
output.Add($"[{temp}]");
}
The (*) parts in this code are using the MaxLength property of the DataColumns maximum length in order to get a column-like output.
I would like to do the same in the (**) parts, but I don't know how to access the corresponding DataColumn, starting from the dataRow object.
Does anybody have an idea?
Thanks in advance
You already have the dataTable instance available. dataTable.Columns[i] should give you the appropriate DataColumn.
Datatable has already been instantiated here. If you want to print the datacolumn you should use dataTable.Column[i] for the appropriate column.

Is there a way to get the last non-null values of each column in a C# DataTable and display them as a single row?

I want to take the last non-null values of each column in a DataTable and create a single row with them.
Sample code:
DataTable temp; // temp is the DataTable shown on the left side in the "Current Result" section
DataTable temp2; // stores the newly create DataTable row
foreach(DataRow row in temp.Rows){
object[] Item = new object[] {};
foreach(DataColumn col in temp.Columns){
if (row[col] != null || row[col] != DBNull.Value || !String.IsNullOrWhiteSpace(row[col].ToString()))
{
Array.Resize(ref Item, Item.Length + 1);
Item[Item.Length - 1] = row[col];
}
}
temp2.Rows.Add(Item);
}
My code currently copies all of the cells from one DataTable to another, including the cells that don't have any values stored in it.
Current Result:
In the photo below, I blacked out all the cells except of the last non-values of each column. I want the shown values to be stored and displayed as a single row.
Desired Result:
I don't know if the problem is solved. Her are my suggestion to solve the problem. I would go from the last row up to the first, because the task is to have the last value from each column and then the loop is may be erlier finish, as when you go from the top to the bottom of the table. But this I think also depends on the data in the table.
DataTable temp = yourTable; // the original table
DataTable temp2 = new DataTable();
object[] lastNonNullValues = new object[temp.Columns.Count];
// Index of the last row.
int lastRow = temp.Rows.Count - 1;
// Get from the last row to the first
for (int i = lastRow; i >= 0; i--)
{
// Don't know if necessary but if all columns has an value -> finish.
if (lastNonNullValues.All(x => x != null)) break;
DataRow row = temp.Rows[i];
for (int j = 0; j < temp.Columns.Count; j++)
{
// Continue if some value was written
if (lastNonNullValues[j] != null) continue;
// None of this condition should be true, thas why should change from || to &&
if (row[j] != null && row[j] != DBNull.Value && !string.IsNullOrWhiteSpace(row[j].ToString()))
{
lastNonNullValues[j] = row[j];
}
}
}
temp2.Rows.Add(lastNonNullValues);
Notice:
The solution of Rufus L should also be work when change the if statement from or to and-conjunction.
It seems to me that you're just looking to add a single row to the temp2 table, which has the last non-null value for each column. If that's the case, then you can initialize the object[] with the Columns.Count size, and we can loop through the columns using the column index, which allows us to assign a new value to an existing column when we find a non-null value for it in the current row:
DataTable temp = new DataTable();
DataTable temp2 = temp.Clone();
// A single row of data that is 'Columns.Count' long
object[] lastNonNullValues = new object[temp.Columns.Count];
foreach (DataRow row in temp.Rows)
{
// Loop through columns using the column index rather than a foreach
for (int i = 0; i < temp.Columns.Count; i++)
{
var col = temp.Columns[i];
if (row[col] != null || row[col] != DBNull.Value ||
!string.IsNullOrWhiteSpace(row[col].ToString()))
{
// Now we just assign the value at the index for this column
lastNonNullValues[i] = row[col];
}
}
}
// Add our single row to the results table
temp2.Rows.Add(lastNonNullValues);

Efficiently check if any cell in a DataTable contains a substring

I am using the code below to allow a user to filter a DataTable by searching a particular string that could be in any column or any row. The code needs to delete rows where the value doesn't exist as the DataTable is exported after the operation.
The problem with this code is two-fold: 1) it is extremely slow for larger tables, and 2) it can only find the complete contents of a cell (i.e. if the column "Name" has a row where the value is "Andrew" the user should be able to search "drew" or "and" and get that result; right now it will return that row if they search "Andrew").
if(!String.IsNullOrEmpty(combo1Text) || !String.IsNullOrEmpty(combo2Text)
&& !String.IsNullOrEmpty(search1Text) && !search1Text.Contains("Type your search for" + comboText + "here"))
{
for (int i = tab1table.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = tab1table.Rows[i];
if (!dr.ItemArray.Contains(search1Text))
{
dr.Delete();
tab1table.AcceptChanges();
}
percentprogress++;
worker.ReportProgress(percentprogress);
}
}
What is the best way to do the filtering I want (and do so efficiently, so that it's not just looping through everything)?
To search if a cell content contains the searched text, try the following code:
for (int i = tab1table.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = tab1table.Rows[i];
if (!dr.ItemArray.Any(x=>(x as string).Contains(search1Text)))
{
dr.Delete();
}
percentprogress++;
worker.ReportProgress(percentprogress);
}
tab1table.AcceptChanges();
If you have any column that isn't of string type, you should replace (x as string) to x.ToString()

Get column name by value of field in datarow

My question is actually more about optimizing something I already have working.
I'm having a hard time believing there isn't a better way to do this with a LINQ query or lambda expression, so I thought I'd try here.
Each of my datatable rows has an item number and 43 quantity columns, that each correspond with a specific day. What I'm trying to do is take each row, and find the first quantity column that is greater than 0 and return that column name. My solution does work, but I'd really like to make it more efficient:
foreach (DataRow r in dt.Rows)
{
for (int i = 3; i <= dt.Columns.Count - 1; i++)
{
tempCol = dt.Columns(i).ColumnName.ToString();
rowValue = Convert.ToInt32(r(tempCol));
if (rowValue > 0)
{
tempCol = tempCol.Replace("Apat", "");
break;
}
}
var FirstAvailableDate = WorkDate.AddDays((dec)tempCol).ToShortDateString;
//use data in someway
}
Thanks for any suggestions ahead of time!!
the current code, each row * each column
get name of column
store it in variable
in match case perform String.Replace
my suggestion:
var allCols = dt.Columns
.Cast<DataColumn>()
.Select(col => col.ColumnName.Replace("Apat", ""))
.ToArray();
foreach (DataRow r in dt.Rows)
{
var firstCol =
r.ItemArray.Select((cell, position) => Tuple.Create(Convert.ToInt32(cell), position))
.FirstOrDefault(tuple => tuple.Item1 > 0);
if(firstCol == null) continue;
var colName = allCols[firstCol.Item2];
var FirstAvailableDate = WorkDate.AddDays((dec)colName).ToShortDateString;
//use data in someway
}
Please change following code
Tuple.Create(Convert.ToInt32(position), cell)
var colName = allCols[firstCol.Item1];
Working fine...!!!

how to compare 2 datatable and get unique records in 3rd datatable?

I have 2 datatable let say dtData1 and dtData2. I have records in both the datatable I want to compare both the data table and want to create a new datatable let say dtData3 with uniqe records.
suppose: dtData1 has 10 records, and dtData2 has 50 records, but what ever records are there in dtData2 in that 7 records are same as dtData1. So here I want unique records in dtData3, means I want only 43 records in dtData3.
we don't know in datatable where we have the duplicate, and its possible that we will not have duplicates or its also possible that we will have all duplicate records.
So in dtData3 I need unique records
Some one please help me.
var dtData3 = dtData2.AsEnumerable().Except(dtData1.AsEnumerable(), DataRowComparer.Default);
Use this.. Probably it will help you.
Suppose you have two data table
DataTable dt1 = new DataTable();
dt1.Columns.Add("Name");
dt1.Columns.Add("ADD");
DataRow drow;
for (int i = 0; i < 10; i++)
{
drow = dt1.NewRow();
drow[0] = "NameA" + 1;
drow[1] = "Add" + 1;
dt1.Rows.Add();
}
DataTable dt2 = new DataTable();
dt2.Columns.Add("Name");
dt2.Columns.Add("ADD");
DataRow drow1;
for (int i = 0; i < 11; i++)
{
drow1 = dt2.NewRow();
drow1[0] = "Name" + 1;
drow1[1] = "Add" + 1;
dt2.Rows.Add();
}
Now To solve your problem Call :-
DataTable d3 = CompareTwoDataTable(dt1, dt2);
The method is something like this;--
public static DataTable CompareTwoDataTable(DataTable dt1, DataTable dt2)
{
dt1.Merge(dt2);
DataTable d3 = dt2.GetChanges();
return d3;
}
Then where the need to compare dtData1 and dtData2? Instead you can copy the contents from dtData2 to dtData3 starting from index7.
First Create Array variables to save unique coloumn values for datatable3. Use Foreach loop with second gridview rows. If any match then dnt save it in a array value, if dnt match then save it in arrays. and display it by attaching with third gridview.......
e.g
string[] name = new string[4];
int i=0,j=0;
foreach(GridViewRows gv in GridView1.rows)
{
if(gv.Cells[0].Text == GridView2.Rows[i].Cells[0].Text)' //if match
{
// dnt save
}
else' //if dnt match save in array for further use
{
name[j] = gv.Cells[0].Text;
j= j++;
}
i=i++;
}
After Saving unique values in Array "name"...Bind it in Third Gridview
During DataBound of third Gridview add this method...
Private void GridView3_RowDataBound(object sender,EventArgs e)
{
if(e.Row.RowState == DataControlState.DataRow)
{
foreach(string nm in name)
{
e.Rows.Cells.Add(name);
}
}
}
public DataTable CompareTwoDataTable(DataTable dtOriginalTable, DataTable dtNewTable, ArrayList columnNames)
{
DataTable filterTable = new DataTable();
filterTable = dtNewTable.Copy();
string filterCriterial;
if (columnNames.Count > 0)
{
for (int iNewTableRowCount = 0; iNewTableRowCount < dtNewTable.Rows.Count; iNewTableRowCount++)
{
filterCriterial = string.Empty;
foreach (string colName in columnNames.ToArray())
{
filterCriterial += colName.ToString() + "='" + dtNewTable.Rows[iNewTableRowCount][colName].ToString() + "' AND ";
}
filterCriterial = filterCriterial.TrimEnd((" AND ").ToCharArray());
DataRow[] dr = dtOriginalTable.Select(filterCriterial);
if (dr.Length > 0)
{
filterTable.Rows[filterTable.Rows.IndexOf(filterTable.Select(filterCriterial)[0])].Delete();
}
}
}
return filterTable;
}

Categories