Can we filter Datatable with LINQ? - 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"),
});

Related

Dynamically linq without columns

how can I get all Columns of a tabel via dynamic linq? Is there something like wildcards? For example:
var query = db.myTable.select("*").orderby("Name"); or
var query = db.myTable.select("new { * }").orderby("Name");
and how can I convert the query to a List?
ar query = db.myTable.select("new { * }").orderby("Name").toList();
Thanks

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")));
}

LINQ Where condition against datatable

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;

Best way to get individual days from a column, using LINQ

I have the following data in one MSSQL Table column
2011-06-20 11:53:32.000
2011-06-20 11:54:24.000
2011-06-20 11:55:45.000
2011-08-05 10:24:12.000
2011-08-05 10:25:28.000
2011-08-05 10:26:20.000
2011-08-05 10:27:12.000
2011-08-05 10:28:04.000
2011-08-05 10:28:55.000
Using LINQ, I would like to get the following data from the column
2011-06-20
2011-08-05
So I can put into a List<>
What's the best way to do this? I already have the context stuff setup, so I don't need details on that. I just need an idea of the best "query" and logic I can use to get this data. Thanks!
You are looking for all of the Distinct dates in a range of DateTimes, the following will show examples to get what you need, given you already have them in a string or by querying your database:
Example (with list of strings):
var list; //Contains your dates
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
Example (from database table):
List<String> dates = (FROM d in datesTable
SELECT d.date.ToShortDateString()).Distinct().ToList();
Console Example to demonstrate functionality:
List<DateTime> list = new List<DateTime>();
list.Add(DateTime.Parse("2011-06-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:44:32.000"));
list.Add(DateTime.Parse("2011-04-20 11:53:32.000"));
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
foreach (string date in result)
{
Console.WriteLine(date);
}
Console.Read();
var q = from t in mydates select distinct ( t.Date.ToShortDateString());
To select distinct dates into a list try this:
List<String> myDates = (from t in myTable
select t.myDate.ToShortDateString()
).Distinct().ToList()

Binding LINQ query to DataGridView

This is very confusing, I use AsDataView to bind query result to a dgv and it works fine with the following:
var query = from c in myDatabaseDataSet.Diamond where c.p_Id == p_Id select c;
dataGridView1.DataSource = query.AsDataView();
However, this one results in an Error:
var query = from item in myDatabaseDataSet.Items
where item.p_Id == p_Id
join diamond in myDatabaseDataSet.Diamond
on item.p_Id equals diamond.p_Id
join category in myDatabaseDataSet.DiamondCategory
on diamond.dc_Id equals category.dc_Id
select new
{
Product = item.p_Name,
Weight = diamond.d_Weight,
Category = category.dc_Name
};
dataGridView1.DataSource = query.AsDataView();
Error:
Instance argument: cannot convert from
'System.Collections.Generic.IEnumerable<AnonymousType#1>' to
'System.Data.DataTable'
AsDataView doesn't show up in query.(List). Why is this happen? How to bind the query above to the dgv then?.
The signature of the AsDataView is as follows:
public static DataView AsDataView(
this DataTable table
)
The only parameter is the DataTable.
The query you have is returning an IEnumerable of an anonymous type which doesn't have an implicit conversion to a DataTable (or a sequence of DataRow instances, in which case you could use that to help you create a DataTable).
You need to get the results back into a DataTable or something you can convert into a DataTable and then it will work.
In your particular case, it seems that you were (or are) using typed DataSets. If that is the case, then you should be able to take the values that were selected and then create new typed DataRow instances (there should be factory methods for you) which can then be put into a typed DataTable, which AsDataView can be called on.
just simply convert the result to a list and bind it to your grid.
var query = from item in myDatabaseDataSet.Items
where item.p_Id == p_Id
join diamond in myDatabaseDataSet.Diamond
on item.p_Id equals diamond.p_Id
join category in myDatabaseDataSet.DiamondCategory
on diamond.dc_Id equals category.dc_Id
select new
{
Product = item.p_Name,
Weight = diamond.d_Weight,
Category = category.dc_Name
}.ToList();
dataGridView1.DataSource = query;

Resources