LINQ Where condition against datatable - linq

I have a DataTable. I would like to filter DataRows where City = "Hongkong".
How to apply LINQ against DataRow?

You could use the following Query
var filter = testTable.AsEnumerable().
Where(x => x.Field<string>("City") == "HongKong");

var result = dr.Where(r => r.Field<string>("City") == "Hongkong");

Using LINQ to DataSets, you can do the following:
DataTable table;
var rows =
from row in table.AsEnumerable()
where row.Field<string>("City") == "Hongkong"
select row;

Related

Summing and grouping in datatable

1.Requirement:
the above is the result of my datatable value
1. Need to group the states by summing the premium value
2. need to mention the address, city for the states which is having highesht premium values
3. Linq or for loop anything is fine for me, please help me out
thanks,
Srikanth Anantharaman
You could use this LINQ query to fill a second table:
DataTable newTable = tbl.Clone(); // empty table, same schema
var groupedByState = tbl.AsEnumerable()
.GroupBy(r => r.Field<string>("State"));
foreach(var group in groupedByState)
{
DataRow maxPremRow = group.OrderByDescending(r => r.Field<int>("Premium")).First();
DataRow newRow = newTable.Rows.Add();
newRow.SetField("State", group.Key);
newRow.SetField("Address", maxPremRow.Field<string>("Address"));
newRow.SetField("City", maxPremRow.Field<string>("City"));
newRow.SetField("Premium", group.Sum(r => r.Field<int>("Premium")));
}

Filter list having two Tables join data in Entity Framework

I have two tables..
Student (StudentId,Name,FatherName)
Qualification (QualificationId,StudentId,DegreeName)
I have got data like this..
var myList = (from c in entities.Students
join q in entities.Qualifications on c.StudentId equals q.StudentId
select new {c.Name,c.FatherName,q.DegreeName}).ToList();
Now i want to filter myList more.. How can i do it, like..
var filteredList = myList.Select(c=> new Student
{
Name=c.Name,
FatherName=c.FatherName
//Degree=C.Degree
}).ToList();
The above Linq Query is not working if i want to get DegreeName also, My Question is how to further Filter myList.
Thanks.
var filteredList = myList.Where(i => i.FatherName == "Shahid").ToList();
Keep in mind since you called ToList() on the original query you are now filtering in memory. If you want to filter in the database then remove the ToList() on the first query and do it like this:
var myList = from c in entities.Students
join q in entities.Qualifications on c.StudentId equals q.StudentId
select new {
c.Name,
c.FatherName,
q.DegreeName
};
var filteredInDatabase = myList.Where(i => i.FatherName == "Shahid").ToList();

how to Sort Gridview At A Pageload itself?

I have this code of mine on pageload, please have a look:
var d = from p in db.Questions
where p.CatId == Convert.ToInt32(s)
select p;
DataTable datatable =d as DataTable;
DataView dataview = new DataView(datatable);
dataview.Sort ="id DESC" ;
GridView1.DataSource =dataview;
GridView1.DataBind();
I have a column named "id" in the table "Questions" on which I want to sort the gridview on pageload itself.
The following Error shows up during compilation:
DataTable must be set prior to using DataView.
Please Help.
well, I already Figured out the answer. Here is the code which I inserted
var d = from p in db.Questions
orderby p.Dtime descending
where p.CatId == Convert.ToInt32(s)
select p;
DataTable datatable =d as DataTable;
DataView dataview = new DataView(datatable);
dataview.Sort ="id DESC" ;
GridView1.DataSource =dataview;
GridView1.DataBind();

Can we filter Datatable with LINQ?

Suppose my datatable is filled with data.
After filling data can we again put some condition on datatable with linq to extract data.
Suppose my datatable has 10 employee record.
So can we extract only those employee whose salary is greater than 5000 with linq query.
I know that we can achieve it datatable.select(). How can you achieve this with linq?
You can get a filtered set of rows, yes:
var query = table.AsEnumerable()
.Where(row => row.Field<decimal>("salary") > 5000m);
This uses the AsEnumerable and Field extension methods in DataTableExtensions and DataRowExtensions respectively.
Try this:
var query = (from t0 in dtDataTable.AsEnumerable()
where t0.Field<string>("FieldName") == Filter
select new
{
FieldName = t0.Field<string>("FieldName"),
FieldName2 = t0.Field<string>("FieldName2"),
});

Iterating Linq result set using indexers

Let's ay I have this query:
var results = from row in db.Table select row;
How can I access this:
string name = results[0]["columnName"];
if you really want a particular index you can use the Skip() method with First().
var rowOffset = 0;
var results = (from row in db.Table
select row).Skip(rowOffset).First()["columnName"];
But unless you are using a Where clause I would really recommend using the indexer. The indexer is pretty much a direct reference while the LINQ statement would be using the objects iterator.
Also don't forget you can do much more advanced stuff with LINQ.
var rowOffset = 0;
var pageLength = 10;
var results = (from row in db.Table
let colValue = row["columnname"]
where colValue != null
select colValue.ToString()
).Skip(rowOffset)
.Take(pageLength)
.ToArray();
var commaString = string.Join(", ", results);
If you specifically just want the zeroth element, you can use results.First()
results is a IEnumerable list of Rows. So you can get it with a simple foreach.
foreach(var row in results)
{
string name = row["columnName"];
}
(from row in db.Table select row).First().columnName

Resources