2016-11-23 112 views
0

我想與LINQ更換的foreach循環在下面的代碼的ForEach()表達:Foreach循環在LINQ在C#

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

任何幫助請!

+2

有一個[類似的問題(http://stackoverflow.com/questions/200574/linq-equivalent-of-foreach-for- ienumerablet) – lloyd

+0

看起來像你需要添加一個類型聲明爲名稱,像「var Name = db ...」 –

+0

@lloyd - 這個問題**不是**重複。 C#關鍵字'foreach'和'.ForEach'擴展方法之間有區別。 – Enigmativity

回答

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

哪個只會碰到數據庫一次。

+0

太棒了!非常感謝!!它按預期工作! – TanvirArjel

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

這將在SQL生成報表,從而只是做一個選擇。

需要注意的一件事是IN的性能隨着集合(本例中爲idList)變大而降低。在大集合的情況下,您可以批量設置並執行多個查詢:

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

請問您可以給您的答案添加解釋,以便將來的讀者也可以學習* how * it的作用? –

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

或者更好的是:refactorise和選擇...

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

List<string> nameList = db.Books 
    .Where(x => idList.Contains(x.BookId)) 
    .Select(x => x.BookName)) 
    .ToList(); 
-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); 
});