Hi I created this Linq query
var k = from account in _session.All<AccountDetail>()
join subscriber in _session.All<Subscriber>() on account.ID equals subscriber.AccID
join subscriberServices in _session.All<SubscriberServce>() on subscriber.ID equals subscriberServices.UserID
join paymentMethod in _session.All<PaymentMethod>() on subscriberServices.PaymentMethod_ID equals paymentMethod.ID
join paymentFrequency in _session.All<PaymentFrequency>() on subscriberServices.PaymentFrequency_ID equals paymentFrequency.ID
group account by new {AccID= account.ID,paymentFrequency= paymentFrequency.Description,paymentMethod= paymentMethod.Description} into G
select new GenerateInvoiceData() { AccID = G.Key.AccID};
I don't understand
group account by new {AccID= account.ID,paymentFrequency= paymentFrequency.Description,paymentMethod= paymentMethod.Description} into G
why do I specify account when I'm not restricted to it in the anonymous type i.e. I can type paymentFrequency.Description.
The group account part is saying what you want the elements in each group to be. The by new { ... } is what you want the key for each group to be. That's not restricted to being part of the information in an element.
As a simplest example, you might have:
from person in people
group person.FirstName by person.LastName
which would give you groups where the key of each group was the last name of all the people represented in the group, and each element of each group would be the first name of someone.
You might want to read two of my Edulinq blog posts:
How query expressions work
The GroupBy method
Related
I want to do a group join with the following three tables using linq extension methods
Custumer
Order
OrderShippingInfo
Custumer can have many Orders and each order can have only one OrderShippingInfo.
So my goal is do a group join of these 3 tables and return a anonymous object that has one Customer and an array of {Order, OrderShippinfo}.
I know how to do a groupjoin between customer and order but I don't know how to add the OrderShippInfo in the collection
Customer.GroupJoin(Order, c=>c.customerID, o=>o.CustomerID, (c,o)=> new {c,o})
Thanks a lot
How about that:
Customer.GroupJoin(Order.Join(OrderShippinInfo,
o=>o.OrderID,
s=>s.OrderID,
(o, s) => new { Order = o, ShippingInfo = s}),
c=>c.customerID,
oi=>oi.Order.CustomerID,
(c,oi)=> new {c,oi})
I have two entities who are N:N - related with each other. With an example I'll show you what I mean :
I have a Session (ave_Session) and there we can put "Trainers"
(ave_trainer) on each Session
I'm tryting to get a list of al the
"Trainers" for a particular Session
They are related to each other in
N:N (relationship name : ave_ave_session_ave_trainer)
I work in VS2010 and with C# => I'm trying to get the data through LINQ
I recently just started with LINQ, so maybe you guys can help me out on this one. The following I've tried and i gave me an "AttributeFrom and AttributeTo must be either both specified or both ommited. You can not pass only one or the other. AttributeFrom: , AttributeTo: ave_trainerid"-error :
var formatteurs = (from f in ORGContext.CreateQuery<ave_trainer>()
join s in ORGContext.CreateQuery<ave_ave_session_ave_trainer>() on f.Id equals s.ave_trainerid.Value
join c in ORGContext.CreateQuery<ave_session>() on s.ave_sessionid.Value equals c.Id
where c.Id == item.Id
select f).ToList();
The item.id is the Id of the session. Thx in advance if you can help me out!
From the MSDN page:
// List the contacts in the Softball team marketing list.
System.Console.WriteLine("List all contacts in Softball Team:");
var members = from c in crm.contacts
join mlm in crm.listmembers on c.contactid equals mlm.entityid
join ml in crm.lists on mlm.listid equals ml.listid
where ml.listname == "Softball Team"
select c;
foreach (var c in members)
{
System.Console.WriteLine(c.fullname + " " + c.emailaddress1);
}
It seems a little backwards the way you have it written now (assuming I'm parsing it correctly).
What you'd normally do is put your 'starting thing' first and then go through the mapping to get to the ones you want. I don't have any CRM 2011 experience, so hopefully I didn't mess this up too much. :)
Also, I'm not a fan of single-character names, so I took the liberty of using longer names :)
var formatteurs = (
// first get the session we're interested in
from session in ORGContext.CreateQuery<ave_session>()
where session.Id == item.Id
// now get the mapping rows that are related to it
join mapping in ORGContext.CreateQuery<ave_ave_session_ave_trainer>()
on session.Id equals s.ave_sessionid.Value
// now get from the mapping rows to the actual trainers
join trainer in ORGContext.CreateQuery<ave_trainer>()
on mapping.ave_trainerid.Value equals trainer.Id
select trainer
).ToList();
I have 3 tables: DiaryPosts, DiaryImpressions, Impressions.
Impressions is a small list with some fields: 'like', 'dislike', 'agree', 'disagree'. The user can vote according to what he thinks about the post.
DiaryImpressions is the table that handles the relationship between the posts and the users who vote.
My problem is, I have to count results of each impression vote for each post, so maybe for one post 13 users voted for like, 2 for dislike, 34 agree and 1 disagree.
I have no idea how to perform the query in some way I can get this specific count results for each impression.
Can anyone help me with that?
You can do this via the GroupBy method. It allows you to automatically "group" the elements based on the impression, and count the results per group.
var post(from c in posts selec c)
string post1like;
string post2dislike;
string postagree3;
string postdisagree3;
foreach (var item in posts)
{
var ipressionslike=(from c in imressions where impressioid=item.id where c.impressionID='LIKE' select c.userID).Tolist()
var ipressionsdislike=(from c in imressions where impressioid=item.id where c.impressionID='disLIKE' select c.userID).Tolist()
var ipressionslike=(from c in imressions where impressioid=item.id where c.impressionID='LIKE' select c.userID).Tolist()
var ipressionsagree=(from c in imressions where impressioid=item.id where c.impressionID='disLIKE' select c.userID).Tolist()
post1like+=item.id+""+ipressionsdislike.count;
post2dislike+=item.id+""+ipressionslike.count;
postagree3+=item.id+""+ipressionsagree.count;
}
it should count the impressions for each post and count the amount of users that like or dislike so if you have 30 people dislike for each post it should get them I cannot see your table structure but I hope it will help or point you somewhere
I have to guess but here is what I think the SQL would look like:
SELECT I.Name, COUNT(I.Name)
FROM DairyPosts P
JOIN DairyImpressions DI ON P.ID=DI.DairyID
JOIN Impressions I ON DI.ImpressionsID = I.ID
And what the linq would look like:
List<Dairy> dairyposts = GetDairyPosts();
var impressionCounts =
from p in dairyposts
group p by p.ImpressionName into g
select new { Type = g.Key, ImpressionCount = g.Count() };
Of course I have to assume your list is created a certain way, if you can post how your list is actually created that would help. (As I said in the comments)
I am trying to translate this into Linq and cannot figure it out:
SELECT
CustomerOrder.ShipState, MONTH(OrderFulfillment.OrderDate) AS Mnth,
YEAR(OrderFulfillment.OrderDate) AS Yer,
SUM(OrderFulfillment.Tax) AS TotalTax
FROM
OrderFulfillment INNER JOIN
CustomerOrder ONOrderFulfillment.OrderID =CustomerOrder.OrderID
WHERE
(OrderFulfillment.Tax > 0)
GROUP BY
CustomerOrder.ShipState, MONTH(OrderFulfillment.OrderDate),
YEAR(OrderFulfillment.OrderDate)
ORDER BY
YEAR(OrderFulfillment.OrderDate) DESC, CustomerOrder.ShipState,
MONTH(OrderFulfillment.OrderDate) DESC
I have Linqpad and have gone through a bunch of the examples but cannot figure this out.
I think you want to do something like this:
from c in CustomerOrder
join o in OrderFulfillment on c.OrderId equals o.OrderId
where
o.Tax > 0
group o by
new { c.ShipState, Mnth = of.OrderDate.Month, Yer = of.OrderDate.Year }
into g
orderby
g.Key.Yer descending, g.ShipState, g.Key.Mnth descending
select
new { g.Key.ShipState, g.Key.Mnth, g.Key.Yer,
TotalTax = g.Sum(i => i.Tax) };
I haven't tried to compile it, but I think this is something along the lines of what you want.
The idea is that first you perform your join to link the customers and orders. Then apply your filter condition.
At that point, you want to get all the orders that have a particular group, so the group operator is applied.
Finally, order the results, then select out all info from the keys for each group, and sum up the tax in each of the group.
First of all, it would be nice to know what exactly you can't figure out. If you're completely lost and don't know where to begin then you need to google around for linq joining and grouping.
Here's something I did recently that may (possibly) point you in the right direction:
// This groups items by category and lists all category ids and names
from ct in Categories
join cst in Category_Subtypes
on ct.Category_Id equals cst.Category_Id
join st in Subtypes
on cst.Subtype_Id equals st.Subtype_Id
where
st.Type_Id == new Guid(id)
group ct by new { ct.Category_Id, ct.Display_Text } into ctg
select new
{
Id = ctg.Key.Category_Id,
Name = ctg.Key.Display_Text
}
With class RoleRecord (Guid RoleId, string RoleName,...) I am trying to get a new list of Name where the RoleId matches a list of Guid
IEnumerable<RoleRecord> roles;
IEnumerable<Guid> roleIds;
I was thinking about avoiding the nested for loops, and along the lines of :
var query =
from rowA in roles
join rowB in roleIds
on rowA.RoleId equals rowB.????
select { rowA.RoleName };
I tried to wrap the guid in a class too, but cant even build it because the syntax is wrong.
Any ideas?
Thanks
I would personally not use Jeremy's answer if you've got a significant number of Guids. If a join is what you really want to express - you just need:
var query = from rowA in roles
join rowB in roleIds on rowA.RoleId equals rowB
select rowA.RoleName;
Alternatively, create a set of role IDs first:
HashSet<Guid> validRoleIds = new HashSet<Guid>(roleIds);
var query = from rowA in roles
where validRoleIds.Contains(rowA.RoleId)
select rowA.RoleName;
The advantage is that then you don't need to do a linear search through every valid role ID for every role. That's not an issue if you know you don't have many roles or role IDs, but generally a hashing approach will be more effective.
Note that the join will use a hash as well internally.
Give this a try:
var query =
from rowA in roles
where roleIds.Contains(rowA.RoleId)
select rowA.RoleName;