2017-08-10 16 views
-5

LINQを使用して文字列を整数に変換するにはどうすればよいですか?LINQでasp.net mvc stringをintに変換するには?

私がこれまでに試したことは以下を参照してください。

public ActionResult ViewStudent() 
{ 
var std = from s in db.Students 
      select new StudentViewModel() 
      { 
      student_id = s.student_id, 
      student_name = s.student_name, 
      student_age =s.student_age, 
      student_address = s.student_address 
      }; 

    var age = std.Average(s => Convert.ToInt32(s.student_age));//error 
    var nostd = std.Count(); 
    ViewBag.totalstd = nostd; 
    ViewBag.stdage = age; 

    return View(std); 
} 
+1

にロードあなたがどのような問題が発生しているだろうことにかかわらず、注意してください?あなたは問題を説明しません。 –

+0

文字列をintに変換する方法LINQ to Entitiesは、 'Int32 ToInt32(System.String)'メソッドを認識せず、このメソッドをストア式に変換することはできません。 – BijayDhimal

+1

あなたの質問を最初からそこにあったはずの追加情報を提供するように[編集]してください。 –

答えて

0

整数に解析可能な文字列のリストがあるとします。

など、すべての値が「123」のような「変換可能」の文字列であることが必要であることを考慮して取る、あなたに匹敵する整数のリストを純益ます
List<string> intList = new List<string>() { "1", "2" }; 
List<int> convertedList = intList.Select(x => Convert.ToInt32(x)).ToList(); 

EDIT:あなたはそれを平均化したい場合あなたの構文は間違っています。 あなたが最初と平均の後を変換する必要があります。

double avg = intList.Select(x => Convert.ToInt32(x)).Average(); 
+0

それをasp.net mvc – BijayDhimal

+0

asp.net mvcに変換する方法はすべて意図した目的のためにC#です。これはLINQを使用して文字列のリストを整数に変換する方法です。 〜これはあなたが探しているものではない場合は、あなたの質問に詳細を与える必要があります。 –

+0

別のオプションは 'intList.Select(int.Parse).ToList();' –

1

あなたは次の操作を行うことができます。

方法INT32に解析しようとする:

public static int ParseInt32(string str, int defaultValue = 0) 
{ 
    int result; 
    return Int32.TryParse(str, out result) ? result : defaultValue; 
} 

そして、あなたのLINQ文で、やるとこの:

var age = std.Average(s => ParseInt32(s.student_age)); 
+0

student_ageは文字列です。 – BijayDhimal

+0

[OK]をクリックし、私の提案するソリューションを使用してください。これはあなたのために働くでしょう。ParseInt32は渡された文字列(student_age)をintに解析しようとします。成功した場合はintを返し、そうでなければ0を返します。あなたは例外とエラーを避けるでしょう –

+0

ああalaa_Sayegn私はasp.net mvcの新機能です。私はLINQクエリを使用しています。私はどのクエリがasp.net mvcでより良いSQLクエリまたはlinqクエリであるか混乱しています。 – BijayDhimal

3

Linq to Entities変換方法がわからないConvert.ToInt32SQLに変換する。

年齢の列がstringではなくintになるようにデータベースを更新することもできます。

ToList()を使用すると、Linq to Objectsを使用することができます。

したがって、このような何か:

public ActionResult ViewStudent() 
{ 
    var std = (from s in db.Students 
     select new StudentViewModel() 
     { 
     student_id = s.student_id, 
     student_name = s.student_name, 
     student_age =s.student_age, 
     student_address = s.student_address 
     }).ToList(); 

    var age = std.Average(s => Convert.ToInt32(student_age)); 
    var nostd = std.Count(); 
    ViewBag.totalstd = nostd; 
    ViewBag.stdage = age; 

    return View(std); 
} 

これはデータベースにdb.Studentsテーブルからすべてを選択し、メモリ

関連する問題