让我看看我是否理解...您有一个包含用户信息的数据库查找表,并且您想要所有用户 ID 列表中的所有用户名?除非您进行更多处理,否则您根本不需要 foreach 循环。我怀疑甚至可以在选择中完成。试试这个 linq 语句...
List<string> UserNameList = context.KULLANICILAR.Where(x=> MyIntegerIdValues.Contains(x.UserId)).Select(x=>x.UserName).ToList();
作为完整的 LinqPad 示例,请查看以下代码。输出也在下面......
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
要遍历列表列表,您只需将字符串列表定义移到 foreach 循环之外,然后添加范围。
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();
}