Reputation: 65
I have two Lists:
using (DBEntities context = new DBEntities()) {
var userInfoList = context.UsersInfoes.ToList();
var membersList = context.Members.ToList();
}
These two list are represented on tables as below;
I want to be able to iterate through both lists WHERE THE TEAMID is equal to '10' and add FKUserID and Name to a third list where FKUserID is matching in both tables.
Is there anyway I can do this as efficiently as possible and produce these results in the third list?
Upvotes: 2
Views: 719
Reputation: 5175
You could use a linq join clause as follows:
var ThirdList =
from member in MembersList
join userInfo in UserInfoList on member.FKUserID equals userInfo.FKUserID
where member.TeamID == 12 // change 12 to the TeamID needed
select new { TeamID = member.TeamID, FKUserID = member.FKUserID, Name = userInfo.Name};
foreach(var tlist in ThirdList)
{
Console.WriteLine("{0} | {1} | {2}", tlist.TeamID, tlist.FKUserID, tlist.Name);
}
Output:
12 | 6 | kjh
12 | 7 | ghg
12 | 8 | dfi
Upvotes: 1
Reputation: 21
I haven't tested this LINQ but it should work. You said you wanted TeamID = 10, but used 12 in your tables. Obviously, just change the 12 to whatever you want the TeamID to be.
var ThirdList = (from y in userInfoList join z in membersList on y.FKUserID equals z.FKUserID
where z.TeamID == 12
select new {
TeamID = z.TeamID,
FKUserID = z.FKUserID,
Name = y.Name
} ).ToList();
Upvotes: 0