CodeConverter
CodeConverter copied to clipboard
VB -> C#: Conversion removes LINQ Group By names, causing duplicate name error
This code is modified for brevity. Apologies if I made a technical mistake with the C# "group new by" code - the point is just the field names.
VB.Net input code
results.AddRange(From pCurrent In db.Policies
Join agent In db.Entities On agent.Entity_ID Equals pCurrent.Agent_Entity_ID
Join insured In db.Entities On insured.Entity_ID Equals pCurrent.Insured_Entity_ID
Group By
Agent_First_Name = agent.First_Name,
Agent_Last_Name = agent.Last_Name,
Insured_First_Name = insured.First_Name,
Insured_Last_Name = insured.Last_Name Into Group1 = Group
Select
Agent_First_Name = Agent_First_Name,
Agent_Last_Name = Agent_Last_Name,
Insured_First_Name = Insured_First_Name,
Insured_Last_Name = Insured_Last_Name)
Erroneous output
results.AddRange(from pCurrent in db.Policies
join agent in db.Entities on pCurrent .Agent_Entity_ID equals agent.Entity_ID
join insured in db.Entities on pCurrent .Insured_Entity_ID equals insured.Entity_ID
group new {pCurrent, agent, insured} by new { agent.First_Name, agent.Last_Name, First_Name = insured.First_Name, Last_Name = insured.Last_Name } into Group
select new { Agent_First_Name, Agent_Last_Name, Insured_First_Name, Insured_Last_Name });
Notice that it changed the Group field names that I had assigned in VB, and then it tries to select the correct field names instead of the wrong ones it assigned (Insured) or failed to assign (Agent). It also removed the line breaks, which makes it a bit harder to read.
Visual studio error on the Group By field names:
CS0833 An anonymous type cannot have multiple properties with the same name
Expected output
results.AddRange(from pCurrent in db.Policies
join agent in db.Entities on pCurrent .Agent_Entity_ID equals agent.Entity_ID
join insured in db.Entities on pCurrent .Insured_Entity_ID equals insured.Entity_ID
group new {pCurrent, agent, insured} by new {
Agent_First_Name = agent.First_Name,
Agent_Last_Name = agent.Last_Name,
Insured_First_Name = insured.First_Name,
Insured_Last_Name = insured.Last_Name
} into Group
select new {
Agent_First_Name,
Agent_Last_Name,
Insured_First_Name,
Insured_Last_Name
});
Details
- Product in use: e.g. VS extension
- Version in use: 9.0.2.0