Let me see if I understand... you have a DB lookup table with user info and you want all the user names from a list of all the user ids? You dont need a foreach loop at all unless you are doing more processing. I suspect even that could be done in the select. Try this linq statement...
List<string> UserNameList = context.KULLANICILAR.Where(x=> MyIntegerIdValues.Contains(x.UserId)).Select(x=>x.UserName).ToList();
As a full LinqPad sample check out the below code. The output is below also...
public class KULLANICILARItem {
public int UserId {get;set;}
public string UserName {get;set;}
}
void Main()
{
// Fake DB Context
List<KULLANICILARItem> KULLANICILAR = new List<KULLANICILARItem>() {
new KULLANICILARItem() {
UserId = 1,
UserName = "Bob"
},
new KULLANICILARItem() {
UserId = 2,
UserName = "Jane"
},
new KULLANICILARItem() {
UserId = 3,
UserName = "Soner"
},
};
// Fake ID List
List<int> MyIntegerIdValues = new List<int>() {
1, 2, 3
};
List<string> UserNameList = KULLANICILAR.Where(x=> MyIntegerIdValues.Contains(x.UserId)).Select(x=>x.UserName).ToList();
UserNameList.Dump();
}
Output:
Bob
Jane
Soner
To loop over a list of lists, you need only move the string list definition outside of the foreach loop and then add range.
public class KULLANICILARItem {
public int UserId {get;set;}
public string UserName {get;set;}
}
void Main()
{
// Fake DB Context
List<KULLANICILARItem> KULLANICILAR = new List<KULLANICILARItem>() {
new KULLANICILARItem() {
UserId = 1,
UserName = "Bob"
},
new KULLANICILARItem() {
UserId = 2,
UserName = "Jane"
},
new KULLANICILARItem() {
UserId = 3,
UserName = "Soner"
},
new KULLANICILARItem() {
UserId = 4,
UserName = "Jim"
}
};
List<string> UserNameList = new List<string>();
foreach(var StringIdValues in new string[] { "1,2", "3,4"} )
{
List<int> MyIntegerIdValues = StringIdValues.Split(',').Select(i => int.Parse(i)).ToList();
UserNameList.AddRange(KULLANICILAR.Where(x=> MyIntegerIdValues.Contains(x.UserId)).Select(x=>x.UserName).ToList());
}
UserNameList.Dump();
}