3
Answers

How to iterate through result where one field is collection

Janie Lane

Janie Lane

9y
953
1
Hi,

I'm tranforming a SQL query to linq or Lambda, then I get this result where one property is a collection of objects. So basically I only have 2 properties in my object. First property is the purchase ID, the second property is a collection of employee ID . The result in LINQ is an anonymous type having fields PurchaseID and a collection of EmployeeID. My problem is assigning the value and returning it as a list of EmployeePurchases object. 

class EmployeePurchases
{
PurchaseID int {get; set;}
EmployeeID int {get;set;}
}

My attempt on this is questionable since running the SQL query and comparing the result vs. the result of this code below does not match.
Sorry I'm very new to Linq/Lambda.

...result variable is the output of Entity Framework selection from DB

var results = (from q in result
where q.EmployeeID.Any()
select new {StaffCollection = q.EmployeeID, PurchaseID = q.PurchaseID }).ToList();


var col = new List<EmployeePurchases>();
foreach (var i in results)
{
var x = new EmployeePurchases();
var seq = i.StaffCollection.GetEnumerator();
x.PurchaseID = i.PurchaseID;
while (seq.MoveNext())
{
x.EmployeeID = seq.Current.EmployeeID;
col.Add(x);
}

}
return col;

Thanks in advance.


Answers (3)