Filtering columns in datatable - c#

I have a datatable with multiple columns. I want to filter the columns for which i do:
newDatableName= OldDt.ToTable(false,"col1","col2");
Now suppose, I want to specify the column names dyanamically i.e put all the column names in a string and then Do:
string colnames= "col1,col2";
newDatableName= OldDt.ToTable(false,colnames);
I tried the above but it does not work. I even tried:
string colname= "\"col1\",\"col2\"";
but it considers the string of column names as one column and gives the error that no such column present.
Any help appreciated.

I suppose that you are using the DataView.ToTable method (so OldDT is a DataView not a DataTable).
In this case you need to pass an array of your column names
string[] colnames = new string[] {"col1", "col2"};
newDatableName= OldDt.ToTable(false,colnames);

you can use Steve's answer, if don't like defining a new array try this:
string colnames="col1,col2"
newDatableName=OldDt.ToTable(colnames.Split(',');

DataTable.DefaultView.ToTable(bool, Params string[] ColumnNames);
The above Method creates and returns a new DataTable based on rows in an existing DataView.
You have to passes two parameters to this function.
If true, the returned DataTable contains rows that have distinct values for all its columns. The default value is false.
A string array that contains a list of the column names to be included in the returned DataTable . The DataTable contains the specified columns in the order they appear within this array.
For Example:
DataTable NewTable = dt.DefaultView.ToTable(false, "StartDate", "FinishDate", "ItemName", "AssigneeNames", "ProjectName", "PercentComplete");

Related

How to Take Dynamic datatable last row is in first row order like that all rows in asp.net

I have created,
DataTable date= new DataTable();
date.Columns.Add("datenmoth");
and made fill the column name "Month" with date as
Month(Column name)
05-oct-2014
06-Nov-2014
02-Dec-2014
02-jan-2015
01-feb-2015
20-mar-2015
and made fill my dynamic table
Now, i want this dynamic table data to be Reverse order
i need result in: based on month and year taking reverse order
Month(Column name)
20-mar-2015
01-feb-2015
02-jan-2015
02-Dec-2014
06-Nov-2014
05-oct-2014
Thank you.
Don't fill this table with strings but with DateTimes. If you use string as column-type you always have to convert it to a DateTime. Like here:
var dateInReversedOrder = date.AsEnumerable()
.OrderByDescending(r => DateTime.Parse(r.Field<string>("datenmoth")))
.CopyToDataTable();
That works but is inefficient and prone to localization issues (in future).
Sample data and (desired) result after sorting in descending order:
DataTable date = new DataTable();
date.Columns.Add("datenmoth");
date.Rows.Add("05-oct-2014");
date.Rows.Add("20-mar-2015");

Get Dataset information in C#

I have an Dataset (XSD) with many datatables. How can I get informations about this datatables? for example I want to get all columns and its captions from a specific datatable.
When I use dataset_X.datatable_Y.... there are no properties like "colums" and so on.
I only get "Equals", "GetDataTableSchema", "GetTypedSchema" and "Reference Equals".
You need to create an instance of your strongly typed DataSet.
For example:
var ds = new dataset_X();
DataColumnCollection columns = ds.datatable_Y.Columns;
or, if you want informations of a specific column, you can also use the auto generated property. Assuming there's a column with a name idSparePart, there's automatically a property idSparePartColumn.
DataColumn col = ds.datatable_Y.idSparePartColumn;
String columnName = col.ColumName;
Type t = col.DataType;
// and so on...
You can try with this code - based on GetXmlSchema
string schemaString = dataSet.GetXmlSchema();
Link : http://msdn.microsoft.com/en-us/library/41732z18.aspx

How to get unique records of specific columns of data table

I have a DataTable imported from Excel file.
Data i need is only unique from specific columns of the DataTable.
The unique data i meant is like when a command DISTINCT is used in SQL Select Query.
I want to get the list of the unique data from the DataTable Column and put them into List
I think LinQ can be used for this matter but i'm not so familiar with it.
I was thinking of code like this below
var data is from MyDataTable
where MyDataTable.ColumnName = "SpecificColumn"
select MyDataTable["SpecificColumn"]).UniqueData;
List<string> MyUniqueData = new List<string>();
foreach(object obj in data)
{
if(MyUniqueData.NotContain(obj))
MyUniqueData.add(obj);
}
I hope someone can drop off some knowledge to me.
var unique = data.Distinct().ToList();
What you're looking for is .Distinct(). See MSDN documentation here. You can specify your own comparer if you need something specific and it will return only unique records.
If you have a Datatable or DataView, inorder to get unique records from a column, you have to write this.
this would be simple.
DataTable dtNew = dt.DefaultView.ToTable(true, "ColName"); // for Datatable
DataTable dtnew= dv.ToTable(true, "ColName"); // for DataView

C# Datatable woes

I have a database command that populates a DataTable I want to get the value of an entry in the Datatable, based on, A: The numeral index of the row, and b, the string name of the column. That's all I want, how is that possible?
yourDatatable.Rows[rowIndex]["columnName"] should work
myTbl.Rows[0]["b"];
A is not a row index.
DataTable dt = GetData();
var result = dt.Rows[RowIndex]["MyColumnName"];
The RowIndex is an indexed property of the datatable which returns a DataRow. "MyColumnName" is an indexed property of the DataRow, returning the value as an object.

How to remove more DataTable Columns using C#.Net?

I have One DataTable may have more Columns. But "NetAmount", "TotalAmount", "Destination" are the DataTable Columns which always present in the DataTable.
Here I want to Remove the three Columns such as "NetAmount", "TotalAmount" and "Destination" from the DataTable and to take the other column values in the DataTable.
I tried like the below and get the Desired Output.
dtAttribute.Columns.Remove("NetAmount"); //dtAttribute is the Main DataTable
dtAttribute.Columns.Remove("TotalAmount");
dtAttribute.Columns.Remove("Destination");
DataTable dtItem = dtAttribute.Copy();
But it looks like very childish and lengthy. Is there any other method to do? Please give suggestions.
There's nothing wrong with your code (except that you are copying the table after removing the columns -- are you sure that this is what you want?).
If you want something more abstract (instead of repeating the same line again and again), you might consider removing the columns in a loop:
var dtItem = dtAttribute.Copy(); // if you want to keep a copy of the original table
var toRemove = new string[] {"NetAmount", "TotalAmount", "Destination"};
foreach (col in toRemove)
dtItem.Columns.Remove(col);
Instead of removing the columns, how about not putting them in the DataTable in the first place?
First select columns which you want to remove, then remove them
List<string> toRemove = dt.Columns.Cast<DataColumn>().Where(c => c.ColumnName.StartsWith("ExtraColumn")).Select(c => c.ColumnName).ToList();
foreach (var col in toRemove) dt.Columns.Remove(col);

Categories