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;
Related
I have seen in other posts for how to filter table records using '<' '=' conditions but I want to use mysql inbuilt functions like,
date,yearweek etc,
datatable table; //--> it contains my result
DataRow[] foutput = table.Select("YEARWEEK(Date) = 'YEARWEEK(CURRENT_DATE)'");
gvweeksch.DataSource = foutput;
gvweeksch.DataBind();
You cannot use database functions in a DataTable which only suports few methods. Have a look at expression-syntax in following link to see what is supported:
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.110).aspx
Note that a DataTable is just an in-memory colection which does not even know the source of the data. It's neither related nor linked with a database.
If you want to filter the table with complex conditions like the week of the year you should use Linq-To-DataTable instead where you have all .NET methods:
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar cal = dfi.Calendar;
int week = cal.GetWeekOfYear(DateTime.Today, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
var rowsFiltered = from row in table.AsEnumerable()
let date = row.Field<DateTime>("Date")
where date.Year == DateTime.Today.Year
&& week == cal.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek)
select row;
DataTable tblFiltered = table.Clone(); // empty table with same columns
foreach (DataRow row in rowsFiltered)
tblFiltered.ImportRow(row);
gvweeksch.DataSource = tblFiltered;
gvweeksch.DataBind();
That consist of 2 columns: roomType and no rooms
So I want to get no rooms value from room type that i have.
In SQL its look like this:
SELECT no_rooms from table name where roomtype = 'deluxe'
Result: 2
How to access that in LINQ query and store that value as int datatype?
I only know this code
string[] tableName = table.AsEnumerable()
.Select(s => s.Field<string>("NoRooms"))
.ToArray<string>()
.Where(?idont_know_the_query));
var results = from myRow in table.AsEnumerable()
where myRow.Field<String>("roomtype ") == "deluxe"
select myRow;
Here is just another way of retriving the data rows, assuming that table in your example is a DataTable
string expression = string.Format("roomtype='{0}'","deluxe");
var rows = dt.Select(expression);
var strRoomNumber = rows.Select(r=>r.Field<string>("roomNumber")).FirstOrDefault();
int no_rooms;
int.TryParse(strRoomNumber,out no_rooms);
This will return you the first no of rooms for the first matching record
var NoOfRooms= tablename.where(x=>x.roomType=="deluxe").ToList();
int total = NoOfRooms.count();
I have 100 records in my Datable says to be in
DataTable dt=new DataTable();
dt have 100 of records say column name as sub_id(contain int datatype) and subheadername(contain nvarchar(150)) , I want top 20 records from this dt in ascending order
I am putting code as
//dtlcategories.DataSource = dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataBind();
Here dtlcategories is Datalist but on running error is coming as 'System.Data.DataRow' does not contain a property with the name 'subheadername'.
ANSWER IS SOLVED
dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).copytodatatable();
dtlcategories.DataBind();
There's a couple different ways you can do this using LINQ. These will both return the same results.
dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20);
dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20);
If you're going to use the result as the source of data for another control, you may need to call .ToList() after .Take(x).
Edit:
I changed the column name based on your edit. If you want to sort by id instead (you didn't specify), just replace "subheadername" with "sub_id".
This query fetches top 20 records from db and then orders them by the sub_id column.
var topTwenty = dt.AsEnumerable().Take(20).OrderBy(r => r.Field<int>("sub_id"));
dt.AsEnumerable().OrderBy(row => row["sub_id"]).Take(20);
This will return you IEnumerable. Now iterate through the IEnumerable and add them to another data table. Now your final data table is ready!!
this code orders data according to date and takes first 100 row.
var table = new DataTable();
var t = table.AsEnumerable();
var result = t.OrderByDescending(f => f.Field<DateTime>(new DataColumn("Date"))).Take(100);
Update:
var table = new DataTable();
var t = table.AsEnumerable();
var result = t.OrderBy(f => f.Field<String>(new DataColumn("subheadername"))).Take(20)
A possible solution:
DataRow[] rows = dt.Select("sub_id< 100 ");
I want to apply the follwing Sql query in my DataTable
SELECT MakeDistinct AS AfterDistinct
, COUNT(MakeDistinct) AS Count
FROM MyTable
GROUP BY MakeDistinct
Refer this Question for more details
something like:
var query = from row in table.AsEnumerable()
group row by row.Field<int>("MakeDistinct") into grp
select new {AfterDistinct = grp.Key, Count = grp.Count()};
foreach(var row in query) {
Console.WriteLine("{0}: {1}", row.AfterDistinct, row.Count);
}
Note that aggregating at the database server will usually be much more efficient than populating a DataTable over the network and then aggregating the DataTable.
You are partially looking for DataTable.Compute. That method can calculate aggregate functions for you. So you get something like:
object sumObject;
sumObject = myDataTable.Compute("Sum(Count)", ""); // second parameter is the where clause
For grouping by columns, see this question: Efficient DataTable Group By. It provides a Linq implementation as well as a 'non-Linq' implementation.
Use System.Data.DataSetExtensions and try something like this
var result = from row in dt.AsEnumerable()
group row by row.Field<int>("MakeDistinct") into grp
select new
{
MakeDistinct = grp.Key,
Count = grp.Count()
};
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();