2016-04-15 49 views
-1

在我的示例中,我遇到問題可將我的搜索結果添加到一個列表中。我必須展示多個學生,他們在不同的地點。我在foreach聲明中遇到.ToList()問題。它只顯示我的學生從上次的位置。使用搜索參數列表查找值

下面是我的代碼:

public void Search(IEnumerable<string> Location) 
{ 
    Location.ToList(); 

    foreach (var l in Location) 
    { 
     var students = from s in db.Students 
         select s;     

      students = students.Where(s => s.City.Contains(l)); 

     var searched = students.ToList(); 
     int custIndex = 1; 
     Session["Students"] = searched.ToDictionary(x => custIndex++, x => x); 
     ViewBag.TotalNumberStudents = searched.Count(); 
    } 
} 
+0

你如何展示學生?你傳遞給你的「視圖」是什麼? – Ian

+0

在行'Session [「Students」] =搜索...'你在每個迭代(每個位置)分配一個_new_字典。你需要結合這些字典。 –

+0

謝謝大家,據我所知,我必須在foreach循環之前聲明搜索變量,並在foreach之外使用Session [「Students」]和viewbag。但後來我無法訪問students.toList()。有什麼建議麼? –

回答

0

可能是因爲你不斷替換導致了問題的Session["Students"]ViewBag.TotalNumberStudents

Session["Students"] = searched.ToDictionary(x => custIndex++, x => x); 
ViewBag.TotalNumberStudents = searched.Count(); 

因此,只有在年底的最後searched得以通過。

嘗試積累的結果,然後立刻將它們傳遞到Session["Students"]ViewBag.TotalNumberStudents

0

有在你的代碼一些問題,custIndex被循環和Session變量中定義的下一個迭代覆蓋,因此你注意到只會在會議結果中顯示seached結果。

你可以這樣做。

int custIndex =1; 
Session["Students"] = Location.SelectMany(l=> db.Students.Contains(l)) 
           .ToDictionary(x=>custIndex++, x=>x); 

ViewBag.TotalNumberStudents = searched.Count();