I'm beginner in linq to sql, I using the c# linq to sql and wrote this query:
var query_find = (from t in behzad.Interconnect_Traffic_Analysis_Details
where t.FILEID == FILE_ID && t.code_operator.Trim() == item.code_operator.Trim()
select new { t.moddat }).ToList();
I want to calculate sum of the t.moddat column, how can I convert this query to sum the values? Thanks.
t.moddat is a nvarchar(max) datatype and save into that double datatype value.
Try this
var query_find = (from t in behzad.Interconnect_Traffic_Analysis_Details
where t.FILEID == FILE_ID && t.code_operator.Trim() == item.code_operator.Trim()
select new
{
sum= t.moddat
}).ToList();
var sum= query_find.Sum(x => Convert.ToDouble(x.sum));
Related
I am trying to write a linq query for one of my dashboard which retrieves data based on some conditions. I want to display records count based on the different status available in my table.
Following is the SQL query in which I am trying to convert into Linq.
select count(id) cnt, 'Available' label from table where date = sysdate
Above query is returning below result in DB IDE. This is the result I want with linq
cnt label
0 Available
I've tried with following linq query but it is returning 0 count and hence result is not being retrieved.
var data = (from a in context
where a.date = System.DateTime.Now
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).ToList();
How do I achieve above mentioned result in linq. Your help will be appreciated.
Thanks
-------------EDIT----------------
Updated LINQ query
var data = (from a in context.TableA
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'Available'
}).Concat(from a in context.TableB
where a.id = uniqueID
group a in a.id into g
select new {
cnt = g.Count(),
label = 'WIP'
}).ToList();
To count the number of elements matching a predicate in a linq query simply use the where clause:
var results =
from a in context
where a.date.Date == DateTime.Now.Date
&& a.id == someIdHere
select a;
var data = new {
count = results.Count(),
label = "Available"
};
Or, in extension method syntax (which I prefer):
var results = context.Where(a => a.date.Date == DateTime.Now.Date && a.id == someIdHere);
var data = new {
count = results.Count(),
label = "Available"
};
Also be careful when comparing a DateTime object with regards to what results you desire; comparing DateTime.Now to a date will likley return false since it will compare the time code as well, use the DateTime.Date property to obtain only the date from the object for the purposes of comparison.
I'm new to LINQ and I'm not sure how to retrieve data from multiple tables from my SQL server database, here's the query:
SELECT cp.*, tsd.Action, tsd.CurrencyPair
from TradeStatsData tsd, CalculatedPrices cp
where tsd.TradeID = cp.TradeID and cp.Price is null and cp.ActiveTime < GETDATE()
The database uses the variable connection
How can I do this?
Your sql query would be something like this in LINQ:
var result = from tsd in TradeStatsData
join cp in CalculatedPrices on tsd.TradeID equals cp.TradeID
where cp.Price == null && cp.ActiveTime < DateTime.Now
select new
{
CP = cp,
Action = tsd.Action,
CurrencyPair = tsd.CurrencyPair
};
Linq is very similar to sql, just a little backwards.
from tsd in TradeStatsData
join cp in CalculatedPrices on tsd.TradeID equals cp.TradeID
where cp.Price == null && cp.ActiveTime < DateTime.Now
select new { cp.Col1... cp.ColN, tsp.Action, tsp.CurrencyPair }
I am trying to make a linq query to execute this query. The column Additional Data is nvarchar(20) - so linq is reading it as a string
this works fine in SSMS
select SUM(CAST(AdditionalData as smallmoney)) from TransTable
where ActionID = #actID and UserID = uID;
this is my failed attempt at a linq version ( Decimal.Parse() can not be converted to sql from linq i guess)
(from a in Context.TransTable
where a.ActionID == action.ActionID && a.UserID == (long)userId
select decimal.Parse(a.AdditionalData)).Sum();
If the result set isn't too large you could parse the value on the client.
decimal value;
var sum = (from a in Context.TransTable
where a.ActionID == action.ActionID && a.UserID == (long)userId
select a.AdditionalValue).ToList().
Select(x => decimal.TryParse(x, out value) ? value : 0).Sum();
Here's the query I'm trying to convert into Linq:
SELECT R.Code,
R.FlightNumber,
S.[Date],
S.Station,
R.Liters,
SUM(R.Liters) OVER (PARTITION BY Year([Date]), Month([Date]), Day([Date])) AS Total_Liters
FROM S INNER JOIN
R ON S.ID = R.SID
WHERE (R.Code = 'AC')
AND FlightNumber = '124'
GROUP BY Station, Code, FlightNumber, [Date], Liter
ORDER BY R.FlightNumber, [Date]
Thanks for any help.
UPDATE: Here is the Linq code I'm trying it on; I cannot make the OVER PARTITION by Date.
var test =
(from record in ent.Records join ship in ent.Ship on record.ShipID equals ship.ID
orderby ship.Station
where ship.Date > model.StartView && ship.Date < model.EndView && ship.Station == model.Station && record.FlightNumber == model.FlightNumber
group record by new {ship.Station, record.Code, record.FlightNumber, ship.Date, record.AmountType1} into g
select new { g.Key.Station, g.Key.Code, g.Key.FlightNumber, g.Key.Date, AmmountType1Sum = g.Sum(record => record.AmountType1) });
Execute query first without aggregation:
var test =
(from record in ent.Records join ship in ent.Ship on record.ShipID equals ship.ID
orderby ship.Station
where ship.Date > model.StartView && ship.Date < model.EndView && ship.Station == model.Station && record.FlightNumber == model.FlightNumber
select new {ship.Station, record.Code, record.FlightNumber, ship.Date, record.AmountType1};
Then calculate sum
var result =
from row in test
select new {row.Station, row.Code, row.FlightNumber, row.Date, row.AmountType1,
AmountType1Sum = test.Where(r => r.Date == row.Date).Sum(r => r.AmountType1) };
This should produce the same effect as database query. Code above may contain errors, because I wrote it only here.
I've answered a similar thread on: LINQ to SQL and a running total on ordered results
On that thread it was like this:
var withRuningTotals = from i in itemList
select i.Date, i.Amount,
Runningtotal = itemList.Where( x=> x.Date == i.Date).
GroupBy(x=> x.Date).
Select(DateGroup=> DateGroup.Sum(x=> x.Amount)).Single();
In you situation, you might have to join the two tables together first while grouping, then run the same concept above on the joined table result.
I am populating a class using Linq to SQL.
What I am trying to do is query my database, return two integer values and subtract the two values from each other, producing the result, but I can't think of a smart way to do it.
What can I do in this case ?
If it is not clear, , then this psuedocode implementation should clarify what functionality I wish for :
DECLARE #currentVal INT, #previousVal INT
#currentVal = SELECT VALUE
FROM Table1
WHERE Date = CURRDATE()
#previousVal = SELECT VALUE
FROM Table1
WHERE Date = MIN(Date)
RETURN #currentVal - #previousVal
But in Linq to SQL, (from o in context.Table1 where Date = currentDate select Value), how can I subtract the other value from this? Is this possible?
I'd stick to having it as a broken out set of queries, because you can then test if the values were actually returned or not and handle the case where too many values are returned:
var currentValResults = (from row in rows
where row.Date == DateTime.Now
select row.Value)
.ToArray();
var previousValResults = (from row in rows
let minDate = rows.Min(r => r.Date)
where row.Date == minDate
select row.Value)
.ToArray();
if (currentValResults.Length == 1 && previousValResults.Length == 1)
{
var diff = currentValResults[0] - previousValResults[0];
}
else
{
// Error condition?
}
Putting it all into a giant linq statement makes too many assumptions (or at least, my implementation does).
Why not simply do a cross join
var query=
from a in Table1 where a.Date == DateTime.Now
from b in Table1 where b.Date == Table1.Min(c=>c.Date)
select a.Amount - b.Amount;
var result=query.First();
Something like this would work to keep it into one trip to the db (Keep in mind this assumes that only two results will be returned):
int[] values = (from o in context.Table1
where Date = currentDate || Date = context.Table1.Min(x => x.Date)
order by Date descending
select value).ToArray();
return values[0] - values[1];
var currentVal = context.Table1.FirstOrDefault(t=>t.Date == DateTime.Now.Date);
var previousVal = context.Table1.FirstOrDefault(t=>t.Date == context.Table1.Min(d=>d.Date));
var result = currentVal - previousVal;
Or
from d in context.Table1
let prevVal = context.Table1.FirstOrDefault(t=>t.Date == context.Table1.Min(d=>d.Date));
where d.Date == DateTime.Now.Date
return new { d - prevVal };