简体   繁体   English

C#中的LINQ中的Foreach循环

[英]Foreach Loop In LINQ in C#

I would like to replace the foreach loop in the following code with LINQ ForEach() Expression: 我想用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);
    }

Any Help Please!! 任何帮助请!

Your code doesn't quite work (you're adding an IEnumerable<string> to a List<string> ). 您的代码无法正常工作(您正在将IEnumerable<string>添加到List<string> )。 You also won't need ForEach , since you're constructing the list: 您也不需要ForEach ,因为您正在构建列表:

You can do this: 你可以这样做:

var nameList = idList.SelectMany(id => db.Books.Where(x => x.BookId == id)
                     .Select(x => x.BookName)).ToList();

But then you're hitting the database for each ID. 但是,然后您要为每个ID访问数据库。 You can grab all the books at once with : 您可以使用一次获取所有书籍:

var nameList = db.Books.Where(b => idList.Contains(b.BookId))
                       .Select(b => b.BookName).ToList();

Which will only hit the database once. 只会打一次数据库。

Why not a select? 为什么不选择呢?

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();

Or better yet: refactorise and select... 或更妙的是:重构并选择...

int[] idList = new int[] { 1, 2, 3 };

List<string> nameList = db.Books
    .Where(x => idList.Contains(x.BookId))
    .Select(x => x.BookName))
    .ToList();
    nameList.AddRange(
             db.Books.Where(x => idList.Contains(x.BookId))
                     .Select(x => x.BookName)
                     .ToList());

This will generate an IN statement in the SQL, thereby only doing a single select. 这将在SQL中生成一个IN语句,从而仅执行一次选择。

One thing to be aware of is the performance of IN degrades as the set (idList in this case) gets bigger. 要注意的一件事是,IN的性能随着集合(在这种情况下为idList)变大而降低。 In the case of a large set, you can batch the set and do multiple queries: 如果是大型集合,则可以批处理集合并执行多个查询:

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;
}

To answer your specific question, you can do this: 要回答您的特定问题,您可以执行以下操作:

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM