我想用LINQ ForEach()表达式替换以下代码中的 foreach 循环:
List<int> idList = new List<int>() { 1, 2, 3 };
IEnumerable<string> nameList = new List<string>();
foreach (int id in idList)
{
var Name = db.Books.Where(x => x.BookId == id).Select(x => x.BookName);
nameList.Add(Name);
}
任何帮助请!!
答案 0 :(得分:5)
您的代码无法正常运行(您正在向IEnumerable<string>
添加List<string>
)。由于您正在构建列表,因此您也不会需要ForEach
:
你可以这样做:
var nameList = idList.SelectMany(id => db.Books.Where(x => x.BookId == id)
.Select(x => x.BookName)).ToList();
然后你就为每个ID点击了数据库。您可以使用以下方式一次性获取所有图书:
var nameList = db.Books.Where(b => idList.Contains(b.BookId))
.Select(b => b.BookName).ToList();
这只会打到数据库一次。
答案 1 :(得分:1)
为什么不选择?
List<int> idList = new List<int>() { 1, 2, 3 };
List<string> nameList = idList
.Select(id => db.Books.Where(x => x.BookId == id).Select(x => x.BookName))
.ToList();
或者更好:重构并选择......
int[] idList = new int[] { 1, 2, 3 };
List<string> nameList = db.Books
.Where(x => idList.Contains(x.BookId))
.Select(x => x.BookName))
.ToList();
答案 2 :(得分:0)
nameList.AddRange(
db.Books.Where(x => idList.Contains(x.BookId))
.Select(x => x.BookName)
.ToList());
这将在SQL中生成一个IN语句,从而只进行一次选择。
有一点需要注意的是,随着set(在这种情况下为idList)变大,IN的性能会降低。对于大型集合,您可以批量处理该集合并执行多个查询:
int start = 0;
int batch = 1000;
while (start < idList.Count())
{
var batchSet = idList.Skip(start).Take(batch);
nameList.AddRange(
db.Books.Where(x => batchSet.Contains(x.BookId))
.Select(x => x.BookName)
.ToList());
start += batch;
}
答案 3 :(得分:-1)
要回答您的具体问题,您可以这样做:
List<int> idList = new List<int>() { 1, 2, 3 };
List<string> nameList = new List<string>();
idList.ForEach(id => {
var Name = db.Books.Where(x => x.BookId == id).Select(x => x.BookName);
nameList.Add(Name);
});