I have data table which has columns namely Amount,StartDate. I am trying to get particular amount value from Amount based on StartDate.
My code is as follows:
DataTable dtt =_dstt.Tables[0];
var res = from r in dtt.AsEnumerable()
where r.Field("StartDate") == Convert.ToDateTime(drpStartYear.SelectedValue));
select r.Field("Amount");
I am getting following error:
The type arguments for method
'System.Data.DataRowExtensions.Field(System.Data.DataRow, int)'
cannot be inferred from the usage. Try specifying the type arguments
explicitly.
_dsst is DataSet which I populate from database.
Is there better way to do it?
Do like this
DataTable dtt =_dstt.Tables[0];
var res = from r in dtt.AsEnumerable()
where r.Field<DateTime>("StartDate") == Convert.ToDateTime(drpStartYear.SelectedValue));
select r.Field<Double>("Amount");
You need to specify the DataType of column like this r.Field<YourType>("ColumnName")
var res = from r in dtt.AsEnumerable()
where r.Field<DateTime>("StartDate") == Convert.ToDateTime(drpStartYear.SelectedValue));
select r.Field<double>("Amount");
DataTable dtt =_dstt.Tables[0];
var res = from r in dtt.AsEnumerable()
where r.Field<type>("StartDate") == Convert.ToDateTime(drpStartYear.SelectedValue));
select r.Field<type>("Amount");
type in <> will be the type of arguement you are using
Related
i want to convert string to dateTime and then compare them, i'm trying to compare 2 datetime stored in an sqllite database, but i still get the error "no such fonction converttodatetime" here is my code:
from x in db.Table<FicheTechnique>()
where Convert.ToDateTime(x.FirstDate) <= Convert.ToDateTime(newDate)
select x;
Here is what you need to do
var data = from r in dt.AsEnumerable()
where Convert.ToDateTime(r["fld name"]) <= Convert.ToDateTime(newDate)
select r;
Your problem is that you need to do dt.AsEnumerable() when you deal with data table. Your data will be enumerable row collection.
Full Example:
DataTable dt = new DataTable();
dt.Columns.Add("a");
dt.Columns.Add("b");
dt.Columns.Add("c");
dt.Rows.Add("1", "01/01/2001", "01:01:2001");
var p = from r in dt.AsEnumerable() where
Convert.ToDateTime(r["b"]) == Convert.ToDateTime("01/01/2001")
select r;
System.Diagnostics.Debug.WriteLine(p.ToList()[0][0]);
Works: Convert.ToDateTime(r["b"])
Fails Convert.ToDateTime(r["c"])
Basically what it means that the SqLite does not understand the function Convert.ToDateTime. This is deferred execution at play.
You can force the execution first before you filter the results. Only use if the table is not large as it will get all re records and then do the filtering.
Try the following:
from x in db.Table<FicheTechnique>().ToList()
.Where Convert.ToDateTime(x.FirstDate) <= Convert.ToDateTime(newDate)
.Select x;
I have looked at Dynamic linq but I am obviously missing something.
I am attempting to import files from one system to another. I have a DataTable loaded from an Excel sheet containing file information. (ExcelDataTable). I also have a HastSet of files that the user would like to import. (FilesToImport). The user selects which information he would like to import from the speadsheet, and those columns are dynamic and selected at runtime. (List VariablesToUpdate). I am joining on my ID in the query but I am not sure how to return the required columns from the datatable.
DataTable dt = new DataTable();
var query =
from excelRow in this.ExcelDataTable.AsEnumerable()
join file in this.FilesToImport.AsEnumerable()
on excelRow.Field<Guid>("ceGuid") equals file.SourceFileIdentifier
select dt.LoadDataRow(new object[]
<COMPLETELY LOST HERE>
, false);
query.CopyToDataTable();
I can work it out if I know what I would like to return using something like;
select new { ImportSourceFilePath = excelRow.Field<string>(filePathColumn)};
but like I said my columns will vary and I won't know until runtime what they are.
Any ideas?
You can use ExpandoObject for your implementation.
Here is a little tutorial for ExpandoObject
What I ended up doing;
var foundExcelRows =
from excelRow in this.ExcelDataTable.AsEnumerable()
join file in this.FilesToImport.AsEnumerable()
on excelRow.Field<Guid>("ceGuid") equals file.SourceFileIdentifier
select excelRow;
for (int i = 0; i < foundExcelRows.Count(); i++)
{
DataRow row = foundExcelRows.ElementAt(i);
// work with this row since I know the columns I expect
}
I want to delete a particular row from a DataTable named dt.
For a table in SQL, I could do something like:
DELETE FROM dt
WHERE BASELINE_FOLDER = baselineSubfolder
AND BASELINE_FILE = baselineFilename
AND BASELINE_CHECKSUM = baselineChecksum;
Is there an equivalent LINQ statement for this?
Assuming you don't have the model's and only a DataTable (this is what I understand from the OP).
//Cast to enumerable of `DataRow` and filter on your condition
var rows = dt.Rows.Cast<DataRow>().Where(row => row["BASELINE_FOLDER"] == baselineSubFolder && row["BASELINE_FILE" == baselineFilename
&& row["BASELINE_CHECKSUM"] == baselineChecksum).ToArray();
//Loop through and remove the rows that meet the condition
foreach(DataRow dr in rows)
{
dt.Rows.Remove(dr);
}
you can convert the data table to list and can use RemoveAt() to do so.
You can convert it to list and use the below code
string baseLineFolder=dt.Rows["BASELINE_FOLDER"].ToString();
string baseLineFile=dt.Rows["BASELINE_FILE"].ToString();
string baseLineChecksum=dt.Rows["BASELINE_CHECKSUM"].ToString();
var dtresult = dt.AsEnumerable();
var result=(from r in dtresult
where(r.Field<string>("BASELINE_FOLDER")!=baseLineFolder)
&&(r.Field<string>("BASELINE_FILE")!=baseLineFile)
&&(r.Field<string>("BASELINE_CHECKSUM ")!=baseLineChecksum)
select r).ToList();
I just started working on a project that requires Linq to Sql, and I have been able to make queries and retrieve data. But right now I need to fill a DataTable with the data I am retrieving.
My first code was the following:
MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
where cust.CustomerName != "Dante"
orderby cust.CustomerName
select new { Name = cust.CustomerName };
So, since I needed to copy the content of my query to a Datatable I tried this:
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();
Then, my code looks like this:
IEnumerable<DataRow> myQuery = from cust in db.Customers.AsEnumerable()
where cust.Name != "Dante"
orderby cust.Name
select new { Name = cust.Name };
DataTable myDataTable = myQuery.CopyToDataTable<DataRow>();
But with this code the compiler raises and error:
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<System.Data.DataRow>
The error is raised at the select word.
So, What am I doing wrong?? What can I do in order to avoid this conversion issue?
Hope someone can help me, thanks in advance.
There is a way to create a DataTable from a result other than IEnumerable<DataRow>, but it is rather involved. Implement CopyToDataTable Where the Generic Type T Is Not a DataRow.
For your case, though, I would recommend doing it the following way. Go back to your original query:
MyDatabase db = new MyDatabase();
var query = from cust in db.Customers
where cust.CustomerName != "Dante"
orderby cust.CustomerName
select new { Name = cust.CustomerName };
Then define your single field DataTable because when you eventually create a DataRow, it needs a schema to work from:
DataTable myDataTable = new DataTable();
myDataTable.Columns.Add(
new DataColumn()
{
DataType = System.Type.GetType("System.String"),
ColumnName = "Name"
}
);
And finally, go through the results of your query and manually add the DataRows to your DataTable.
foreach (var element in query)
{
var row = myDataTable.NewRow();
row["Name"] = element.Name;
myDataTable.Rows.Add(row);
}
The problem is exactly as the error states; your "select" clause is creating instances of an anonymous type with one member, "Name". This anonymous type is not and cannot be a DataRow, so the implicit conversion between what the query produces and the variable you want to set it into fails.
Instead, you should take this query, and for each element of the anonymous type that it returns, add the value as a new DataRow of the DataTable. You cannot just create a new DataRow from scratch; the DataRow class requires a context, namely the parent DataTable, to define the columns the DataRow should have.
This will do i guess
var myQuery = from cust in db.Customers.AsEnumerable()
where cust.Name != "Dante"
orderby cust.Name
select new { Name = cust.Name };
or try this
string[] myQuery = db.Customers.Rows
.Cast<DataRow>()
.Where(r=>r.Name!="Dante")
.Orderby(r=>r.Name)
.Select(r=>r.Field<string>("Name"))
.ToArray()
I have this linq query :
string title = from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title;
and I'd like to extract the field Title (from Database) on the row (rows will be 1, not more, so that's I put on a string and not in a string[].
How can I do it?
VStudio says that DataRow doesnt contain the definition of Title, but the field Title exist on the database.
I making confusion :)
As Frédéric Hamidi said, you don't need LINQ.
However, if you still want to do it that way (overkill) and you know that there is always a single table with a single row, do:
DataSet data = new DataSet();
var table = (from a in data.Tables.Cast<DataTable>() select a).Single();
var row = (from a in table.Rows.Cast<DataRow>() select a).Single();
String title = row.Field<String>("Title");
or
DataSet data = new DataSet();
var table = (from a in data.Tables.Cast<DataTable>() select a).SingleOrDefault();
var row = (from a in table.Rows.Cast<DataRow>() select a).SingleOrDefault();
String title = row.Field<String>("Title");
I used a DataSet because I don't know how your object is structured.
You don't need LINQ since you only want to fetch the Title field of the first row in the collection:
string title = OleDB.DataItems.Tables[0].Rows[0]["Title"];
try
string title = (from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title).First();
Linq returns an enumerable collection as it doesn't know there will be only one item. Calling the First method will return the first item from the query.
Edit: Hang on, I have blatantly missed the problem you originally mentioned (but you'll still need the above)!
A data row contains fields, not properties as such. What you'll need to do is
select r.Field<string>("Title")
So your entire query will be
string title = (from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Field<string>("Title")).First();
It's better to use FirstOrDefault, in case there are no rows:
string title = (from DataRow r in (OleDB.DataItems.Tables[0]).Rows
select r.Title).FirstOrDefault();
Usually, if you need to perform such an action, you would cast the DataRow object to your strongly typed object corresponding with the table in your database.
I assume there is a class "Book" which contains the field "Title":
Book selectedBook = (Book) from DataRow r in (OleDB.DataItems.Tables[0]).Rows[0]
string sTitle = selectedBook.Title;
Hope this helps.