Summing and grouping in datatable - linq

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

Related

finding multiple row indexes from a datagridview with linq

the below answer gets me the first row index but there are cases where there are multiple rows with my where clause. how do i get a "record set" where there multiple rows.
int index = -1;
DataGridViewRow rowx =
dgvMatchErrors.Rows.Cast<DataGridViewRow>()
.Where(r => r.Cells[1].Value.ToString().Equals(intErrorRowid.ToString()))
.First();
index = rowx.Index;
How to find the row ID from datagridview, given a row value?
You can try by removing First() method call in query
DataGridViewRow rowx =
dgvMatchErrors.Rows.Cast<DataGridViewRow>()
.Where(r => r.Cells[1].Value.ToString().Equals(intErrorRowid.ToString())).Select(r=>r);
This gives me a list of all my row index based on my where clause.
List<DataGridViewRow> rows =
dgvMatchErrors.Rows.Cast<DataGridViewRow>().Where(
r => r.Cells[1].Value.ToString().Equals(intErrorRowid.ToString())
).ToList();

How to select count value by linq

I want express sql below by linq
select catalog,queryname,COUNT(*) from doctemplatecells group by catalog,queryname
I don't know how to get count(*), thanks
Every group consists of it's key (catalog, queryname) and it's elements as represented by the IEnumerable<> implementation of the group.
So if you have a group as a result of LinQ, you can call the extension method Count() on it.
var groups = doctemplatecells.GroupBy(dtc => new { Catalog = dtc.catalog, QueryName = dtc queryname });
foreach(group in groups)
{
console.WriteLine("{0} {1} #{2}", group.Key.Catalog, group.Key.QueryName, group.Count());
}

Dynamically adding the columns in group by clause of linq

I am getting a datatable from service. I am using linq to calculate of sum new columns. I want all the coumns in datatable originally plus the new columns calculated in linq.
Problem is columns in datatable are not fixed. How would I dynamically add the columns in select clause of linq.
Below is code snippet:
DataTable dt = ds.Tables[0];
var orderCtr =
from o in dt.AsEnumerable()
where o.Field<string>(Constants.GENDER_NAME) != "Unknown"
group o by new
{
odr_id = o.Field<int>(Constants.ORDER_ID),
//NEED TO ADD COLUMNS DYNAMICALLY HERE. MEANS IF THEY ARE IN DATATABLE.
}
into g
select new
{
//NEED TO ADD COLUMNS DYNAMICALLY HERE. MEANS IF THEY ARE IN DATATABLE.
odr_id = g.Key.odr_id,
ac_gr_imp = g.Sum(r => r.Field<long>(Constants.GENDER_IMPRESSION)),
ac_gr_clk = g.Sum(r => r.Field<long>(Constants.GENDER_CLICK)),
Ctr = (double)g.Sum(r => r.Field<long>(Constants.GENDER_IMPRESSION)) / g.Sum(r => r.Field<long>(Constants.GENDER_CLICK)),
};
You might be interested in the Dynamic LINQ library. Dynamic LINQ allows you to specify queries or parts of queries by building strings.
Scott Guthrie described it back in 2008 (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) and there is also a NuGet package of it in case you use .NET 4 (http://www.nuget.org/packages/System.Linq.Dynamic).

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;

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

Resources