void refreshtable()
{
var query = (from x in de.HeaderTrainingAllocations
join y in de.MsTrainings on x.TrainingID equals y.TrainingID
join z in de.MsUsers on x.UserID equals z.UserID
select new
{
x.AllocationID,
x.TrainingID,
z.UserName,
x.TrainingStartDate,
TrainingEndDate = System.Data.Objects.EntityFunctions.AddDays(x.TrainingStartDate, ((y.TrainingDuration - 1) * 7)),
y.TrainingDuration,
x.Capacity
}
);//get all data from tables
dataGridView1.DataSource = query;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
int currentcapacity;
Int32.TryParse(dataGridView1.Rows[i].Cells[6].Value.ToString(),out currentcapacity);
String idA = dataGridView1.Rows[i].Cells[0].Value.ToString(); //read allocation ID on cell 0
var cek = (from x in de.DetailTrainingAllocations
where x.AllocationID==idA
select x).Count(); //to get amount of data in table detailTransaction
dataGridView1.Rows[i].Cells[6].Value =currentcapacity- cek;//this code won't change the value of the rows in datagridview
}
}
This code is working perfectly but the last code didn't work for some reason,the values in row X at column 6 didn't change at all. I have almost no solution for this in my mind.
This is the most direct conversion, although you really should be doing a JOIN on DetailTrainingAllocations, rather than making a loop, doing one query for each record.
void refreshtable()
{
var query = (from x in de.HeaderTrainingAllocations
join y in de.MsTrainings on x.TrainingID equals y.TrainingID
join z in de.MsUsers on x.UserID equals z.UserID
select new
{
x.AllocationID,
x.TrainingID,
z.UserName,
x.TrainingStartDate,
TrainingEndDate = System.Data.Objects.EntityFunctions.AddDays(x.TrainingStartDate, ((y.TrainingDuration - 1) * 7)),
y.TrainingDuration,
x.Capacity
}
).ToList();//get all data from tables
foreach (var z in query)
{
var cek = (from x in de.DetailTrainingAllocations
where x.AllocationID==z.AllocationID
select x).Count(); //to get amount of data in table detailTransaction
z.Capacity-=cek;//this code won't change the value of the rows in datagridview
}
dataGridView1.DataSource = query;
}
Related
im required to make a query to db to fetch data fro a highchart widget in our site here is the code I use currently,
var highChartsData =
(from a in db.roomdetails
join b in db.ApplySchedule on a.RoomId equals b.RoomID
where b.Status == true
select new HighlinePie
{
Title = a.RoomName,
Date = b.MDate,
Value = db.ApplySchedule.Where(x => x.RoomID == a.RoomId).GroupBy(x=>x.MDate).Count(),
}).ToList();
The problem with this approach is right now get the total count but what i need is the count based on date, for example if there was two entry on date 12/09/20201 and three entry on 14/09/20201 the data should be "Title,12/09/20201,2","Title,14/09/20201,3".
You have to use grouping:
var groupQuery =
from a in db.roomdetails
join b in db.ApplySchedule on a.RoomId equals b.RoomID
where b.Status == true
group b by new { a.RoomName, b.MDate } into g
select new HighlinePie
{
Title = g.Key.RoomName,
Date = g.Key.MDate,
Value = g.Count()
};
var highChartsData = groupQuery.ToList();
In the above diagram for each customer I want to select all orders and then for each order I have calculate a TotalPrice = (Sum of all Food Items included in order * Quantity) + ExtraPrice. I am struggling to create a query for it using linq to sql.
var res = (from a in dc.orders
join b in dc.orderLines on a.orderId equals b.fk_orderId
join c in dc.foodItems on b.fk_foodId equals c.foodId
where a.fk_custId == cID
group new { a,c,b } by a into g
select new
{
OID1 = g.Key.orderId,
date1 = g.Key.date.Value.Date,
price1 = g.Sum(x => x.c.price * x.b.quantity) + g.Key.orderLines.Select(o => o.extraPrice).Sum()
});
Given above is linq query I was looking for.
Should be something close to this. I'm not around a computer to test so let me know if you get errors.
db.orders.Select(o => new { o.orderid, o.date, TotalPrice = ( (o.orderLines.Select(ol => ol.food items.Count()).Sum() * o.Quantity) + o.extraPrice) } )
This question already has answers here:
Create a Tuple in a Linq Select
(6 answers)
Closed 6 years ago.
I have 2 database tables.
In Table1 Calculate I have 1 row which is mapped via an Id to multiple rows in table2 CalculdateData.
Now I need to load the data from table1 Calculate with all relevant Details from Table2 CalculdateData.
How would i have the Details into a Tuple-List.?
So basically for CalculateData I have 4 columns per row which I Need to put into a Tuple. Meaning if I would have for example 4 rows i need to create 4 Tuples in a List.
IEnumerable<Storage> context = new MyEntities();
var Result = (from a in context.calculate
join b in context.CalculateData on a.Id equals b.CalcId into c
where a.SpecialID == 2023 && a.VersionId == 1
orderby a.InternalOrderNr ascending
select new Storage
{
myField1 = a.Field1;
myField2 = a.Field2;
myField3 = a.Field3;
< MISSING PART AND QUESTION >
}).ToList();
return Result;
public class Storage
{
public int myField1;
public int myField2;
public int myField3;
public List<Tuple<int, int, string, decimal>> myField4;
}
This should work:
var Result = (from a in calculate
join b in calculateData on a.Id equals b.CalcId into c
where a.SpecialID == 2023 && a.VersionId == 1
orderby a.InternalOrderNr ascending
select new Storage
{
myField1 = a.Field1,
myField2 = a.Field2,
myField3 = a.Field3,
myField4 = c.Select(d => new Tuple<int, int, string, decimal>
(d.Field1, d.Field2, d.Field3, d.Field4))
.ToList()
}).ToList();
return Result;
It also would be good thing to check that this query transforms in single sql request and you not making new sql request on each tuple list creation.
Edit: In case you will have problems with custom types in query (as #Toxantron pointed) this selection should work:
var queryResult = (from a in calculate
join b in calculateData on a.Id equals b.CalcId into c
where a.SpecialID == 2023 && a.VersionId == 1
orderby a.InternalOrderNr ascending
select new
{
a.Field1,
a.Field2,
a.Field3,
myField4 = c.Select(d => new {
d.Field1, d.Field2, d.Field3, d.Field4})
}).ToList();
result = queryResult.Select(r => new Storage
{
myField1 = r.Field1,
myField2 = r.Field2,
myField3 = r.Field3,
myField4 = r.myField4.Select(t => new Tuple<int,int,decimal,string>
(t.Field1, t.Field2, t.Field3, t.Field4))
.ToList()
})
return Result;
You could try something like this.This is not tested yet.
select new Storage
{
myField1 = a.Field1,
myField2 = a.Field2,
myField3 = a.Field3,
myField4 = c.Select(d => new Tuple<int, int, string, decimal>(d.Field1, d.Field2, d.Field3, d.Field4)).ToList()
}).ToList();
This is totally based on this This tutorial
I would like to convert a SQL statement to LINQ but i have some problems doing it.
The sql statement is :
SELECT
C.[Call_Date], CC.[Company], R.Resolution,
COUNT_BIG(*) AS CNT,
SUM([Duration]) AS Total
FROM
[Calls] C
Join
[CompanyCharges] CC on [Company_Charge] = [CompanyCharge]
Join
[Resolutions] R on C.Call_Resolution = R.Resolution
where
Call_Date >= '05/29/2013'
Group By
C.[Call_Date], CC.[Company], CC.[CompanyCharge], R.Resolution, R.Resolution_Order
I wrote something like :
var stats = from c in dbContext.Calls
join cc in dbContext.CompanyCharges on c.Company_Charge equals cc.CompanyCharge
join r in dbContext.Resolutions on c.Call_Resolution equals r.Resolution
where (c.Call_Date > "05/29/2013")
group new { c, cc, r } by new { c.Call_Date, cc.CompanyCharge, r.Resolution, r.Resolution_Order } into statsGroup
select new { Count = statsGroup.Count(), ??? };
I managed to count the elements, but i need a sum[duration] and some columns from different tables.
Please share your wisdome with me.
Assuming that the [Duration] field is part of the [Calls] table:
var stats = /* ... */
select new
{
Count = statsGroup.Count(),
Total = statsGroup.Sum(stat => stat.c.Duration),
};
You'd probably want to include your grouping fields in the new anonymous type as well:
var stats = /* ... */
select new
{
Call_Date = statsGroup.Key.c.Call_Date,
CompanyCharge = statsGroup.Key.cc.CompanyCharge,
Resolution = statsGroup.Key.r.Resolution,
Count = statsGroup.Count(),
Total = statsGroup.Sum(stat => stat.c.Duration),
};
I have an SQL table with many columns(~200).
I want to create a LINQ query to obtain the sum of all rows by column. The result to be one row which represents the SUM of each column.
How can be done this LINQ query?
It's difficult to create a specific .Sum(...) for each column.
double sum = Table.Select(t => t.Amount ?? 0).Sum();
OR
double sum = Table.Sum(t => t.Amount ?? 0);
You could try using:
var results = (from i in yourCollection
group g by i.Column into g
select new
{
ColumnName = i.Column,
ColumnTotal = i.Sum(x => x.Value)
}).ToList();
Use the right tool for the job. This time it isn't Entity Framework. Here is a simple ADO.NET routine:
public double[] SumAllColumns(IDbConnection connection)
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT * FROM YourTable";
using (var reader = cmd.ExecuteReader())
{
var values = new double[reader.FieldCount];
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
values[i] += reader.GetDouble(i);
}
}
return values;
}
}
}
The method returns an array with the sum of each column.
var sums = (from c in columns
group c by c.columnName into g
select new
{
SumCol1 = g.Sum(x => x.Col1),
SumCol2 = g.Sum(x => x.Col2)
}).SingleOrDefault;
To access the variables in a console application for example...
Console.Write(sums.SumCol1.ToString() + " : " + sums.SumCol2.ToString());
I've used this solution:
from res in datacTx.Table
where ...
group re by re.id into g
select new
{
col1 = g.Sum(x => x.col1),
col2 = g.Sum(x => x.col2),
...
};
but I can't access now any of the values or I can't convert the result into a list in which each column represent an entry in the list.
Until now I've used this, to access the values of linq query:
foreach (var propertyInfo in res.GetType().GetProperties())
{
...
}
but now this is not working because I don't have any properties.
You could use a sqlcommand, which execution returns for each row a result array, then use array.Sum().
Or add a sql computed column.