2016-04-15 19 views
-1

私の例では、検索結果を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

学生をどのように表示しますか?あなたは 'View'に何を渡しますか? – Ian

+0

'Session [" Students "] = searched ...'の行では、(各場所の)繰り返しごとに_new_辞書を割り当てます。これらの辞書を組み合わせる必要があります。 –

+0

ありがとうございます、私が理解しているように、foreachループの前に検索された変数を宣言し、Session ["Students"]とforeachの外にあるviewbagを使用する必要があります。しかし、私は学生には届きません。リスト()。助言がありますか? –

答えて

0

あなたSession["Students"]ViewBag.TotalNumberStudentsを交換し続けるため、問題がありそうな原因です:

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

、最終的には最後searchedが渡されました。

結果を蓄積してみてください、そして、あなたのコード内のいくつかの問題がありSession["Students"]ViewBag.TotalNumberStudents

0

に一度渡し、custIndexは、ループ内で定義されているとセッション変数あなたが気づくしたがって、次の反復でを上書き最後にはseachedという結果だけがセッションに記録されます。

あなたはこれを行うことができます。

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

ViewBag.TotalNumberStudents = searched.Count(); 
関連する問題