How to Get Single Column Value in c# LINQ? - c#

DataTable Master_Table = Execute_Manager.getTableDataSet(connection, select_query, master_table);
string RuleName = (From EachRow in Master_Table
where EachRow.Field<string>("RuleID") == "123456"
Select EachRow.Field<string>("RuleName")).CopyToDataTable().ToString();
I need to get single Column Value using LINQ in Datatable c#

You could do something like the following I have added in the two examples below:
string carManufacturer = "BMW";
DataTable dt = new DataTable();
int id = (from DataRow dr in dt.Rows
where (string)dr["CarManufacturer"] == carManufacturer
select (int)dr["id"]).FirstOrDefault();
string columnValue = dt.Rows[0]["ColumnName"].ToString();
What column value are you trying to fetch from your data table?

Related

should i change data table column datatype after filled with data

I am trying to change data table column datatype using c#.
i have tried like below code :
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
but it throw an exception where fees column come to import.Error Comes Like you can not change datatype of fees column after filled data table.
int startvalue = Convert.ToInt32(lblSelectionStart.Text);
int endvalue = Convert.ToInt32(lblSelectionEnd.Text);
var dv1 = new DataView { Table = dt };
dv1.RowFilter = "fees >=" + startvalue + " and fees <=" + endvalue;
dt = dv1.ToTable();
i want to change fees column into int from string.
If the data in dt came out of a database, modify the database query to perform the int conversion
--oracle example
SELECT to_number(fees) as feesint FROM ...
--sqls example
SELECT convert(int, fees) as feesint FROM ...
--MySQL example
SELECT convert(fees, integer) as feesint FROM ...
If the data in dt did not come from a database, add another column to dt, of type int and parse all the data into it:
dt.Columns.Add("feeint", typeof(Int)32);
foreach(var ro in dt.Rows)
ro["feeint"] = int.Parse((string)ro["fees"]);
Later when you want to put a row filter:
dv1.RowFilter = $"FeesInt >= {startValue} AND FeesInt <= {endValue}";
Remember to use the feesint converted column, not the fees column, which is a string

Check if column exists before execute select clause

I use a DataTable in a foreach loop from sql like:
foreach(var i in tasks)
{
// query sql
var timeOfTasks = db.GetTableBySQL($"exec usp_Get_WorkedProyectTime #TaskTypeCategoryId = '{i.TaskTypeCategoryId}', #TaskId= '{i.TaskId}'");
// read columns (different rows have different columns)
var progressToBackCheck = (from DataRow dr in timeOfTasks.Rows select dr["ProgressToBackCheck"]).FirstOrDefault();
var backcheckToCorrection = (from DataRow dr in timeOfTasks.Rows select dr["BackcheckToCorrection"]).FirstOrDefault();
var correctionsToCompleted = (from DataRow dr in timeOfTasks.Rows select dr["CorrectionsToCompleted"]).FirstOrDefault();
var progressToCompleted = (from DataRow dr in timeOfTasks.Rows select dr["ProgressToCompleted"]).FirstOrDefault();
}
Not all task results have the same data rows. And each row doesn't contain all fields. Is there a way to check if a column exists in the result, before I use query for it?
You can try to use DataColumnCollection.Contains to check the column is exists in the data table.
if (timeOfTasks.Columns.Contains("ProgressToBackCheck"))
{
}
You can use this linq to get field, add where linq
where timeOfTasks.Columns.Contains("ProgressToBackCheck")
look like this.
var progressToBackCheck = (
from DataRow dr in timeOfTasks.Rows
where timeOfTasks.Columns.Contains("ProgressToBackCheck")
select dr["ProgressToBackCheck"]
).FirstOrDefault();

Compare 2 excel columns for similarity and return the matched values in datatable using openxml

I have to compare 2 columns present in different excel sheets and return the matched values using openxml(C#).Both the columns have some account Numbers.
I am able to get the unmatched values using the below code.But I need the matched values.Please suggest.
public static DataTable DocomparisionCOA_ACCT(DataSet dtPrimaryFile, DataSet dtValidationFile)
{
DataTable COA_BU = new DataTable();
DataTable validationsheet1 = dtValidationFile.Tables["COA"];
DataTable primarydatafile = dtPrimaryFile.Tables["JE"];
var qry1 = validationsheet1.AsEnumerable().Select(a => new { bu = a["Acct"].ToString() });
var qry2 = primarydatafile.AsEnumerable().Select(b => new { bu = b["ACCT"].ToString() });
var exceptAB = qry1.Except(qry2);
COA_BU = (from a in validationsheet1.AsEnumerable()
join ab in exceptAB on a["ACCT"].ToString() equals ab.bu
select a).CopyToDataTable();
DataColumn AcctColumn = COA_BU.Columns["Accts"];
return COA_BU;
}

How I can filter my DataTable by Column Value?

I have a question about DataTable. I retrieve a DataTable from the database, and one of these columns contains either a 1 or a 0. Now I want to retrieve only the rows with a 1 value of 1 in that column.
The name of the column is ACTIVATE.
Here is my DataTable:
DataTable table = new DataTable(TABLE);
//How can I filter here so ACTIVATE == 1?
adapter.Fill(table);
connection.Open();
selectcommand.ExecuteReader();
return table;
Via SQL (preferred)
SELECT * FROM dbo.Table WHERE ACTIVATE = 1
Via Linq-To-Datatable (in memory):
DataTable tblFiltered = table.AsEnumerable()
.Where(r => r.Field<int>("ACTIVATE") == 1)
.CopyToDataTable();
If you're still on .NET 2, you can use DataTable.Select:
DataRow[] filteredRows = table.Select("ACTIVATE = 1");
Apart from that, you don't need selectcommand.ExecuteReader() to fill the table.
DataTable table = new Datatable();
using(var con = new SqlConnection(connectionString))
using(var cmd = new SqlCommand("SELECT * FROM dbo.Table WHERE ACTIVATE = 1", con))
using(var da = new SqlDataAdapter(cmd))
{
da.Fill( table );
}
DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();
That should achieve what you want, basically you can query data tables much like SQL.
You simply use DataTable.Select like this:
foundRows = table.Select("ACTIVATE = '1'");
It returns an array of DataRow objects.
return table;
DataTable results = table.Select("ACTIVATE = 1").CopyToDataTable();

How to query C# DataTable?

I have created and returned datatable, this table has 10 columns. Now i want to filter from this table based on some dynamic search parameters. How to do this? any idea would be timely help.
// This function will create and return the source table.
var DisplayTable = CreateQueryTable();
Here I want to do dynamic search like If col1=MyName and Col2=MyCity
ResultGrid.DataSource = DisplayTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);
You can do this in these way,
1.Creating DataView Like
var dv = dataTable.DefaultView;
dv.RowFilter = "col1='MyName' and Col2='MyCity'"; // if MyName and MyCity are literal string.
or
dv.RowFilter = "col1='"+MyName+"' and Col2 ='"+ MyCity +"'";// if MyName and MyCity are string variable.
2.With DataTable Select Method, It will return array of DataRow
var rows = dataTable.Select("col1='MyName' and Col2='MyCity'"); //if string literal
or
var rows = dataTable.Select("col1='"+MyName+"' and Col2='"+MyCity+"'"); // if string variable
3.By Linq
var filterdData = from row in dataTable.AsEnumerable()
where row.Field<string>("col1") == "MyName"
&& row.Field<string>("col2") == "MyCity"
select row;
you create DataView of your datatable and use Filter
// Create a DataView
DataView dv = new DataView(yourDataTable);
dv.RowFilter = "col1='MyName' and Col2='MyCity'";
//Bind your grid with DataView
You can also use select method on your table
DataRow[] foundRows;
foundRows = yourDataTable.Select("col1='MyName' and Col2='MyCity'");
You can also use Linq To DataTable
var results = from myRow in yourDataTable.AsEnumerable()
where myRow.Field<string>("col1") == Myname &&
myRow.Field<string>("Col2") == MyCity
select myRow;

Categories

Resources