Reputation: 1043
I have one table[T1] with this informaions
2nd table[T2] is
Relationship is one user from T1 can have many T2
I want to get result like
My ling to sql is like
var result = (from t1 in context.t1
join t2 in context.UserID on t1.ID equals t2.UserID
select new CLASS
{
ID = t1.ID,
UserID = t1.UserID,
Names = t2.name
}).Take(10).ToList();
But this give me result as each t2.name as separated row. How i can gather all names in array?
LINQ to SQL , ASP.NET C# 4.0
Upvotes: 1
Views: 1137
Reputation: 356
I think something like this should work
var result = (from t1 in context.t1
join t2 in context.UserID on t1.ID equals t2.UserID
select new CLASS
{
ID = t1.ID,
UserID = t1.UserID,
Names = (from t2 in context.t2
select t2.Name
where t2.userID = t1.userID).toArray(),
}).Take(10).ToList();
hope it helps
Upvotes: 1
Reputation: 125620
You have to group your results by ID/UserID:
var result = (from t1 in context.t1
join t2 in context.UserID on t1.ID equals t2.UserID
group by new { t1.ID, t1.UserID } into g
select new CLASS
{
ID = g.Key.ID,
UserID = g.Key.UserID,
Names = g.ToArray()
}).Take(10).ToList();
However, when LINQ to SQL classes are prepared right that kind of queries can be made like:
var result = from t1 in context.t1 select new { id = t1.id, names = t1.t2s.ToArray() };
Upvotes: 0
Reputation: 3276
You don't need to use the join. Create a relationship b/n your two linq entites in the linq designer and then you can run a query like this:
var q = from t in context.t1
select new { id = t1.id, names = t1.t2s.Select(t => t.Name).ToArray() };
Upvotes: 0