我有一个模特:
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;
我应该尝试进行字符串搜索,但是我的代码是不对的。我搜索处理字符串但不清楚的方法。
感谢
答案 0 :(得分: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
,然后它就可以保存文字和数字。您可以进行正则表达式测试以检查它是否包含文本,如果没有,则将其存储的数字转换为int
,以便您使用它。
或者只是制作一个更好的模型,其中包含您需要的所有部分。
您还可以使用.GetType()
返回var
的类型。
<强>更新强>
好的,您现在似乎正在尝试检测dr["Week6"]
是否包含string
或int
。解决这个问题的一种方法是:
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: 包含要转换的数字的字符串。
结果: 当此方法返回时,包含等效的32位有符号整数值 如果转换成功,则为s中包含的数字,如果转换成功则为零 转换失败。如果s参数为null,则转换失败 格式正确,或表示小于System.Int32.MinValue的数字 或大于System.Int32.MaxValue。此参数未初始化传递。
返回: 如果s被成功转换,则为true;否则,错误。