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
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.
Lawrence PondPosted Nov 26, 2014, 1:27 AM
code is here
myItemsGroupedByFruit.SelectMany(p=> p.Category);
Lawrence PondPosted Oct 27, 2014, 10:57 PM
{
// add some data
var epList = new[]
{
new EmployeePurchases { PurchaseID=1, EmployeeID=2},
new EmployeePurchases { PurchaseID=1, EmployeeID=3},
new EmployeePurchases { PurchaseID=1, EmployeeID=4},
new EmployeePurchases { PurchaseID=1, EmployeeID=5},
new EmployeePurchases { PurchaseID=1, EmployeeID=6},
new EmployeePurchases { PurchaseID=1, EmployeeID=7}
};
//Notice how to cast the list as list
List
// mlist is a strongly type List of employeePurchases
}
public class EmployeePurchases
{
public int PurchaseID {get; set;}
public int EmployeeID {get;set;}
}
Janie LanePosted Oct 15, 2014, 10:30 PM
var col = new List
results.ForEach(i =>
{ i.StaffCollection.ForEach(a =>
{
var x = new EmployeePurchases();
x.EmployeeID = a.EmployeeID;
x.PurchaseID = i.PurchaseID;
col.Add(x);
});
});