我想用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);
}
Run Code Online (Sandbox Code Playgroud)
任何帮助请!!
你的代码不太适用(你要添加IEnumerable<string>一个List<string>).您也不需要ForEach,因为您正在构建列表:
你可以这样做:
var nameList = idList.SelectMany(id => db.Books.Where(x => x.BookId == id)
.Select(x => x.BookName)).ToList();
Run Code Online (Sandbox Code Playgroud)
但是你要为每个ID点击数据库.你可以一次抓住所有书籍:
var nameList = db.Books.Where(b => idList.Contains(b.BookId))
.Select(b => b.BookName).ToList();
Run Code Online (Sandbox Code Playgroud)
这只会打到数据库一次.
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |