0

我有一个模型:

public class KPIResults
{
   public virtual string Title { get; set; }
   public virtual int Total { get; set; }
   public virtual  int Week6 { get; set; }
   public virtual  int Week5 { get; set; }
   public virtual  int Week4 { get; set; }
   public virtual  int Week3 { get; set; }
   public virtual  int Week2 { get; set; }
   public virtual  int Week1 { get; set; }

   public virtual string stringWeek6 { get; set; }
   public virtual string stringWeek5 { get; set; }
   public virtual string stringWeek4 { get; set; }
   public virtual string stringWeek3 { get; set; }
   public virtual string stringWeek2 { get; set; }
   public virtual string stringWeek1 { get; set; }
}

在我的报告存储库中,我有:

 int strfound = 0;
 string str = "Number";
 foreach (DataRow dr in dt.Rows)
 {
    string title = dr["Title"].ToString();
    int total = Convert.ToInt32(dr["Total"]);
    if (dr["Week6"].contains("Number")  //synntacs not right?
        var week6 = dr["strWeek6"]
    end

    or do this:
    strfound = str.IndexOf(dr);  //syntacs not right?
    if (strfound == 0)
    {
         var week6 = dr["strWeek6"]
    } 
    var week6 = Convert.ToInt32(dr["Week6"]);
    var week5 = Convert.ToInt32(dr["Week5"]);
    var week4 = Convert.ToInt32(dr["Week4"]);
    var week3 = Convert.ToInt32(dr["Week3"]);
    var week2 = Convert.ToInt32(dr["Week2"]);
    var week1 = Convert.ToInt32(dr["Week1"]);

    results.Add(new KPIResults() {Title = title, Total = total, Week6 = week6, Week5 = week5, Week4 = week4, Week3 = week3, Week2 = week2, Week1 = week1});

  }
  return results;

我也许应该尝试进行字符串搜索,但我在 is 中的代码不正确。我寻找处理字符串的方法,但不清楚。

谢谢

4

1 回答 1

0

有点不清楚你要做什么,回答你的问题,All I want to know is it possible to cast the var type to be stored as an int or the other way around?不。

我认为您最好的选择是使用string它将能够保存文本和数字。您可以进行正则表达式测试以检查它是否包含文本,如果没有,则将其存储的数字转换为 anint以供您使用。

或者只是制作一个更好的模型,其中包含您需要的所有部分。

您还可以使用.GetType()来返回var.

更新

好的,看起来您现在正在尝试检测是否dr["Week6"]包含 astringint. 解决此问题的一种方法是:

int number;
if(int.TryParse(dr["Week6"], out number))
    var week6 = dr["strWeek6"]

如果dr["Week6"]可以转换为int,则该if语句是true并且number将包含 的值dr["Week6"]

这是元数据int.TryParse

摘要:将数字的字符串表示形式转换为其等效的 32 位有符号整数。返回值指示转换是否成功。

参数: s:包含要转换的数字的字符串。

结果:当此方法返回时,如果转换成功,则包含与 s 中包含的数字等效的 32 位有符号整数值,如果转换失败,则返回零。如果 s 参数为空、格式不正确或表示小于 System.Int32.MinValue 或大于 System.Int32.MaxValue 的数字,则转换失败。此参数未初始化传递。

返回:如果 s 转换成功,则返回 true;否则为假。

于 2012-08-23T08:03:26.260 回答