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();
Related
I have a DataTable (dt) with multiple columns which is the source to DataGridView. I am trying to filter this DataTable(dt) with a list of values of a particular column.
I need to filter the Below DataTable(dt) with the list of employee names.
EmpList = {'Pete','Alen'}
This is my DataTable
Employee
ID
Country
Pete
1
USA
Mark
2
UK
Alen
3
AUS
Output needed:
Employee
ID
Country
Pete
1
USA
Alen
3
AUS
I am trying it with the below code
if (EmpList.Any())
{
foreach(string item in EmpList)
{
var dataRows = from dataRow in dt.AsEnumerable()
where (dataRow.Field<string>("Employee").Contains(item))
select dataRow;
dt.Rows.Add(dataRows);
}
}
The problem is With this block of code, DataType(System.Data.EnumerableRowCollection[system.Data.DataRow]) is filling in the Rows of DataTable along with previous Data.
If you want to filter the DataTable, you can use the DefaultView.RowFilter, join the collection of values to be compared and use the IN() operator in the comparison:
var names = new[]{ "Allen", "Pete" };
var values = string.Join("', '", names);
dt.DefaultView.RowFilter = $"Employee IN('{values}')";
Note that the strings are joined using a comma and a single quote: ', '
To remove the filter, just set it to string.Empty.
If you want to return a new DataTable, you can use the CopyToDataTable method:
var dtFiltered = dt.AsEnumerable()
.Where(dr => names.Any(s => s.Equals(dr["Employees"]))).CopyToDataTable();
You can also assign the DataTable to itself:
dt = dt.AsEnumerable().Where(...).CopyToDataTable();
I assume you are already referencing System.Data.DataSetExtensions, since you're using AsEnymerable() in your code.
I have datatable with following columns.
ID
Name
Dept
I want to select Name where ID = "XXX" from datatable.
Can any one please suggest how can i do that.
dt.AsEnumerable().FirstOrDefault(row => row.Field<int>("ID") == 123);
Try this
DataRow[] rows = DataTable.Select("ID = 'XXX'")
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();