Determine if a DataSet column contains entirely identical data - c#

I have a DataSet similar to the one below:
ID Name Data1 Data2
1 MM X 1000
2 ST Y 1000
3 EC Z 1000
4 JT T 1000
I display this DataSet in a DataGridView by binding the DataSet. What I would like to do is set the visibility of the Data2 column based on if all the data is similar or not.
So in the above example, I would want to hide the Data2 column because the data represented is common to all elements in the DataSet. But if any of the elements had a unique entry for that column, I would want the column to be visible.
Is there a way to do this without iterating over the DataSet? I prefer not to iterate as my DataSets are quite large and I want to perform this check for multiple columns.

You can use some LINQ to check to see how many distinct values you have in that column:
if(dataTable.AsEnumerable().Select(row => row["Data2"]).Distinct().Count() > 1)
{
// Make column invisible
}
If there is more than 1 distinct value, then you know that not all of the values are equal.

var areSame = dt.Rows.Count > 0 &&
dt.AsEnumerable().All(x => dt.rows[0]["Data2"].Equlas(x["Data2"]));

Related

Retrieve specific datarow in C# Datatable

I have a datatable in C# called "table" that looks like the following:.
ID Value
10 A
20 B
30 C
(It really has about 1200 rows, but I tried to simplify it)
My goal is to be able to print specific rows in this datatable. For example, if I would like to print the second row (row index 1) I would use the following:
Response.Write(table.Rows[1]["Value"].ToString());
This prints out the value "B" which is what I want, but is there a way to use the "ID" column to print that specific value instead of using the row index of 1. I would like to be able to link ID 10 and Value B together somehow.
If ID is defined as the primary key, this should look up B by its ID key:
Response.Write(table.Rows.Find(20).["Value"].ToString());
If ID isn't setup as a PK (or you want to query another field), you could use a Linq query
var chosenRow = (from row in table.AsEnumerable()
where row.Field<int>("ID") == 10
select row).First();
chosenRow is the first DataRow object that meets the criteria set in the where clause. So you could just:
Response.Write(chosenRow["Value"].ToString());
you can loop trough your datatable using for each, and when the ID equals 10, then you do what you want
would be something like this:
for each row as datarow in datatable.rows
if row.Items["ID"] = 10 Then
//do something
end if

Get data from datatable form one column

The query below will get data from a column to see if the data contains a certain string.
This is string is found in that column I would like to select all of the data within them rows. For example in the the datatable the will be a row with age[10-20] and based on this input string it should output all of the row the string is age
The code does not return any data, nor are there any errors. Is it possible to select a column based on the index ?
var result = excelDataTable.AsEnumerable().Where(data => data.Field<String>(0).StartsWith(queryString));
Data input 1
Age
Data in DataTable
Age[0-8] 1 1 1
Age[9-11] 2 2 2
season[winter] 4 4 4
Based on the input I want to return
Age[0-8] 1 1 1
Age[9-11] 2 2 2
The Field extension method works also with the index of the column:
var result = importedExcelData.AsEnumerable()
.Where(r=> r.Field<String>(0).Contains(first));
You can select the column name with Select method.
var result = importedExcelData.AsEnumerable()
.Where(data => data.Field<String>("All Respondents")
.Contains(first))
.Select(c=>c.Field<String>(0)).ToList();

C#, Finding 2 columns sum together in linq

I am bit new to linq .
How do I get the total sum of two columns in my data table.
Let say 2 columns are A& B . I want numeric sum of entire column A and entire column B
(i.e totalSum= sum(A)+sum(B))
IMP :
If I have any field in either of 2 columns a non numeric field (eg AB,WH,DBNULL) . That field should be considered as zero while summing up the values so that it wont throw any exception.
For each row or the sum of entire column A and entire column B?
In the first case you could do a select:
var resultWithSum = from row in table
select new{
A = row.A, //optional
B = row.B, //optional
sum = row.A + row.B
}
Otherwise you can do:
result = table.Sum(row => row.A + row.B)

Show only selected rows in Gridview

I have DataTable object and am binding it to a gridview in C#.
I have 3 columns in the datatable, say "Flag", "Name", and "Value".
What I want to accomplish is that I want to only show the rows where "flag" fields are set to 0.
So say if I have two rows in the table,
Flag Name Value
------------------
0 tom 100
1 Jane 200
And, I only want to show "tom" and "100" on the gridview.
Is there any way I could do this without creating a new datatable?
Thanks.
Here is an example :
DataTable table = DataSet1.Tables["Orders"];
// Presuming the DataTable has a column named Date.
string expression;
expression = "Date > #1/1/00#";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
You can see example Here
Probably you can take the same Datatable like : table = table.Select(...);
try creating a DataView for your DataTable and send it to your GridView instead of the DataTable. see http://msdn.microsoft.com/en-us/library/system.data.dataview.aspx

Remove columns from DataTable in C#

I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.
Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.
I need to write the values out to a fixed length data file.
Aside from limiting the columns selected to reduce bandwidth and memory:
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.
DataTable dt;
int desiredSize = 10;
while (dt.Columns.Count > desiredSize)
{
dt.Columns.RemoveAt(desiredSize);
}
The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.
So for that, here is what I did, when I came across the same problem.
string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };
foreach (string ColName in ColumnsToBeDeleted)
{
if (dt.Columns.Contains(ColName))
dt.Columns.Remove(ColName);
}
How about you just select the columns you want like this:
Dim Subjects As String = "Math, English"
Dim SubjectData As DataTable = Table.AsDataView.ToTable(True, Subjects.Split(","))

Categories

Resources