Below my query which not working properly could any one help here?
enter code here
var collectionamount = (from u in db.bank_deposit
join pr in db.collections on u.AgentID equals pr.AgentID into g
join agentname in db.agent_master on u.AgentID equals agentname.AgentID
group u by new { u.AgentID } into x
select new collectionwithdeposit
{
AgentName = agentname.AgentName,
DepositedAmount = g.Sum(m => m.DepositedAmount),
CollectionAmount = g.Sum(z => z.AmountReceived),
Balance = g.Sum(u => u.DepositedAmount) - g.Sum(v => v.AmountReceived)
}).ToList();
lstdataModel.Add(dataModel);
}
The variable g does not exists in the scope of your select. This is because of the into keyword. What you are writing is in effect..
var tempEnumerable = from u in db.bank_deposit
join pr in db.collections on u.AgentID equals pr.AgentID into g
join agentname in db.agent_master on u.AgentID equals agentname.AgentID
group u by new { u.AgentID };
var collectionamount = from x in tempEnumerable
select new collectionwithdeposit
{
AgentName = agentname.AgentName,
DepositedAmount = g.Sum(m => m.DepositedAmount),
CollectionAmount = g.Sum(z => z.AmountReceived),
Balance = g.Sum(u => u.DepositedAmount) - g.Sum(v => v.AmountReceived)
}).ToList();
The into keyword in Linq is for creating a new scope.
In fact you really don't want to use into as often as you do
Try this
var collectionAmount = from u in db.bank_deposit
where db.collections.Any(pr => pr.AgentID == u.AgentID)
join agentname in db.agent_master on u.AgentID equals agentname.AgentID
group u by agentname into g
select new collectionwithdeposit
{
AgentName = g.Key.AgentName,
DepositedAmount = g.Sum(m => m.DepositedAmount),
CollectionAmount = g.Sum(z => z.AmountReceived),
Balance = g.Sum(u => u.DepositedAmount) - g.Sum(v => v.AmountReceived)
}
EDITED:
Maybe actually what you want is this...I don't know your table structures. But I am going to assume you have no idea about Linq, and your tables are sane (since my last answer assumed the opposite).
var collectionAmount = from agent in db.agent_master
let depositedAmount = db.bank_deposit
.Where(d => d.AgentID == agent.AgentID)
.Sum(d => c.DepositedAmount)
let collectionAmount = db.collections
.Where(c => c.AgentID == agent.AgentID)
.Sum(c => c.AmountReceived)
select new collectionwithdeposit
{
AgentName = agent.AgentName,
DepositedAmount = depositedAmount,
CollectionAmount = collectionAmount,
Balance = depositedAmount - collectionAmount
}
Related
I have a requirement to sort a list by 1) the number of times a distinct item appears and then 2) if the count of two distinct rows is the same, the most recently used date of that group.
My group by function and sorting by count is working without the date:
(from x in data
group x by new { x.Col1, x.Col2, x.Col3}
into g
let count = g.Count()
select new
{
g.Key.Col1,
g.Key.Col2,
g.Key.Col3,
count
}).OrderByDescending(x => x.count)
However, I have been unable to successfully add the date sort. I was trying to add the date column as an aggregate in the group by expression, but that doesn't work.
(from x in data
group x by new { x.Col1, x.Col2, x.Col3, MaxDate = x.CreatedDateTime.Max()}
into g
let count = g.Count()
select new
{
g.Key.Col1,
g.Key.Col2,
g.Key.Col3,
count,
g.Key.MaxDate
}).OrderByDescending(x => x.count).ThenByDescending(x => x.MaxDate)
I get why it doesn't work, I just can't think of another route to add the secondary sort. Any ideas are appreciated!
This is what you're looking for (I think)
from x in data
group x by new { x.Col1, x.Col2, x.Col3}
into g
let count = g.Count()
select new
{
g.Key.Col1,
g.Key.Col2,
g.Key.Col3,
MaxDate = g.Select(x => x.CreatedDateTime)
.OrderByDescending(d => d).FirstOrDefault(),
count
}).OrderByDescending(x => x.count).ThenByDescending(x => x.MaxDate)
How about:
var ordered = Elev8SnaTowelTables
.GroupBy(x => new { x.Col1, x.Col2, x.Col3 })
.OrderByDescending(g => g.Count())
.ThenByDescending(g => g.Max(x => x.CreatedDateTime));
I have a list which is like below
Name Score Date
S1 2 15/02/2013
S1 4 15/02/2013
S2 0 15/02/2013
My desired out should be
S1 6 15/02/2013
for this i wrote LINQ code as
(from _data in _rawData
group _data by new { _data.Date, _data.Name } into gp orderby gp.Key.Date
select new
{
score = gp.Sum(_score => _score.Score),
store = gp.Max(_store => _store.Name),
Date = gp.Max(_Date => _Date.Date)
}).OrderByDescending(_score => _score.score)
.ToList().
ForEach(item => _timeLiner.Add(new TimeLiner()
{
id = _id++.ToString(),
start = item.auditDate.ToString(),
title = "TopStore: " + item.store
}
I tried with .Take(1).ToList(), Single(), SingleOrDefault(), First() but i failed to get desired output. Instead i am getting as
S1 6 15/02/2013
S2 0 15/02/2013
top is a new range variable, which holds summary data for top score name of a day
from d in _rawData
group d by d.Date into dateGroup
let top = dateGroup.GroupBy(x => x.Name)
.Select(g => new { Name = g.Key, Score = g.Sum(x => x.Score)})
.OrderByDescending(x => x.Score)
.First()
select new
{
Name = top.Name,
Score = top.Score,
Date = dateGroup.Key
}
The following should give you the desired output:
(from _data in _rawData
group _data by new { _data.Date, _data.Name } into gp orderby gp.Key.Date
select new
{
score = gp.Sum(_score => _score.Score),
store = gp.Max(_store => _store.Name),
Date = gp.Max(_Date => _Date.Date)
}).OrderByDescending(_score => _score.score)
.First();
Or, a little bit more readable:
_rawData.GroupBy(x => new { x.Date, x.Name })
.Select(g => new {
Score = g.Sum(x => x.Score),
Store = g.Key.Name,
Date = g.Key.Date
}
.OrderByDescending(x => x.Score)
.First()
I am working on classified ads project I am facing problem to get top categories where most ads are posted every category have sub category also.
I made query but it is working for sub category ads I want if any category have no sub category then parent category ads should counted.
var result = (from c in db.Category
join a in db.Ad on c.CategoryId equals a.CategoryId
where c.ParentId != null
group c by c.ParentId into g
select new { cat = g.Key, a = g.Count() })
.OrderBy(c => c.cat)
.OrderByDescending(a => a.a);
My Category Table is like this
CategoryId ----- ParentId -----Name
How can I do this?
I guess this could be done with separate queries:
Get a list of categories that don't have any parentId set:
var resultsWithoutSubs = from c in db.Category
where c.ParentId == null
&& !result.Any(r => cat == c.CategoryId)
select c;
Based on the list above, repeat the original query:
var counts = from c in resultsWithoutSubs
join a in dbAd on c.CategoryId equals a.CategoryId
group c by c.CategoryId into g
select new {cat = g. Key, a = g.Count};
Then you should be able to Union these the first and the last list and sort the results.
Try this:
var results = db.Category
.Join(db.Ad, cat => cat.CategoryId,
ad => ad.CategoryId, (cat, ad) => new { cat, ad } )
.Where (c => !dbCategory
.Any (d => c.cat.CategoryId == d.ParentId) && c.cat.ParentId == null)
.GroupBy (c => c.cat.CategoryId)
.Select (g => new
{ cat = g.Key, a = g.Count () }
);
I am trying to do a relatively straight forward SQL query with linq:
SELECT ir.resource_id, r.first_name, r.surname, rt.job_title, SUM(plan_ts_hours), SUM(ts_hours) FROM tbl_initiative_resource ir
INNER JOIN tbl_resource r ON ir.resource_id = r.resource_id
INNER JOIN tbl_resource_type rt ON rt.resource_type_id = r.resource_type_id
LEFT JOIN tbl_plan_timesheet pts on pts.resource_id = ir.resource_id AND pts.initiative_id = ir.initiative_id
LEFT JOIN tbl_timesheet ts on ts.resource_id = ir.resource_id AND ts.initiative_id = ir.initiative_id
WHERE ir.initiative_id = 111
GROUP BY ir.resource_id, r.first_name, r.surname, rt.job_title
After reading this blog: http://smehrozalam.wordpress.com/2010/04/06/linq-how-to-build-complex-queries-utilizing-deferred-execution-and-anonymous-types/
I came up with the following linq:
var query = (from initRes in Context.tbl_initiative_resource
join res in Context.tbl_resource on initRes.resource_id equals res.resource_id
join resType in Context.tbl_resource_type on res.resource_type_id equals resType.resource_type_id
from tsheet in Context.tbl_timesheet.Where(x => x.resource_id == initRes.resource_id).Where(x => x.initiative_id == initRes.initiative_id).DefaultIfEmpty()
from plannedtsheet in Context.tbl_plan_timesheet.Where(x => x.resource_id == initRes.resource_id).Where(x => x.initiative_id == initRes.initiative_id).DefaultIfEmpty()
where initRes.initiative_id == initiativeID
group new { ID = res.resource_id, ResourceType = resType.job_title, Times = tsheet, P = plannedtsheet } by initRes.resource_id into g
select new
{
ResourceID = g.Key,
Hours = g.Sum(x => (decimal?)x.Times.ts_hours),
PlannedHours = g.Sum(x => (decimal?)x.P.plan_ts_hours)
}).ToList();
Any ideas on how I can access the ResourceType when selecting the new anonymous type?
ResourceType is part of the the grouping key, so g.Key.ResourceType should do it.
(Check out the type of ResouceID in the results, as you've assigned it g.Key it will be an instance of the (anonymous) type created in the group clause.
I have a linq statement which calls a stored proc and returns a list of items and descriptions.
Like so;
var q = from i in doh.usp_Report_PLC()
where i.QTYGood == 0
orderby i.PartNumber
select new Parts() { PartNumber = i.PartNumber, Description = i.Descritpion.TrimEnd() };
I then have another SQL statement which returns the quantities on order and delivery date for each of those items. The Parts class has two other properties to store these. How do I update the existing Parts list with the other two values so that there is one Parts list with all four values?
UPDATE
The following code now brings out results.
var a = from a1 in db.usp_Optos_DaysOnHand_Report_PLC()
where a1.QTYGood == 0
orderby a1.PartNumber
select new Parts() { PartNumber = a1.PartNumber, Description = a1.Descritpion.TrimEnd() };
var b = from b1 in db.POP10110s
join b2 in db.IV00101s on b1.ITEMNMBR equals b2.ITEMNMBR
//from b3 in j1.DefaultIfEmpty()
where b1.POLNESTA == 2 && b1.QTYCANCE == 0
group b1 by new { itemNumber = b2.ITMGEDSC } into g
select new Parts() { PartNumber = g.Key.itemNumber.TrimEnd(), QtyOnOrder = g.Sum(x => Convert.ToInt32(x.QTYORDER)), DeliveryDue = g.Max(x => x.REQDATE).ToShortDateString() };
var joinedList = a.Join(b,
usp => usp.PartNumber,
oss => oss.PartNumber,
(usp, oss) =>
new Parts
{
PartNumber = usp.PartNumber,
Description = usp.Description,
QtyOnOrder = oss.QtyOnOrder,
DeliveryDue = oss.DeliveryDue
});
return joinedList.ToList();
Assuming your "other SQL statement" returns PartNumber, Quantity and DeliveryDate, you can join the lists into one:
var joinedList = q.Join(OtherSQLStatement(),
usp => usp.PartNumber,
oss => oss.PartNumber,
(usp, oss) =>
new Parts
{
PartNumber = usp.PartNumber,
Description = usp.Description,
Quantity = oss.Quantity,
DeliveryDate = oss.DeliveryDate
}).ToList();
You can actually combine the queries and do this in one join and projection:
var joinedList = doh.usp_Report_PLC().
Where(i => i.QTYGood == 0).
OrderBy(i => i.PartNumber).
Join(OtherSQLStatement(),
i => i.PartNumber,
o => o.PartNumber,
(i, o) =>
new Parts
{
PartNumber = i.PartNumber,
Description = i.Description,
Quantity = o.Quantity,
DeliveryDate = o.DeliveryDate
}).ToList();
And again: I assume you have PartNumber in both returned collections to identify which item belongs to which.
Edit
In this case the LINQ Query syntax would probably be more readable:
var joinedList = from aElem in a
join bElem in b
on aElem.PartNumber equals bElem.PartNumber into joinedAB
from abElem in joinedAB.DefaultIfEmpty()
select new Part
{
PartNumber = aElem.PartNumber,
Description = aElem.Description,
DeliveryDue = abElem == null ? null : abElem.DeliveryDue,
QtyOnOrder = abElem == null ? null : abElem.QtyOnOrder
};
Your DeliveryDue and QtyOnOrder are probably nullable. If not, replace the nulls by your default values. E.g. if you don't have the element in b and want QtyOnOrder to be 0 in the resulting list, change the line to
QtyOnOrder = abElem == null ? 0 : abElem.QtyOnOrder