里面的Linq catch异常 [英] Catch exception inside Linq
问题描述
我在C#-code有这个问题。我让我的LINQ代码中的异常,并想知道如何抓住它。的我已搜查左右,但找不到任何相关问题的
I have this problem in my C#-code. I get an exception inside my Linq-code and would like to know how to catch it. I have searched SO but cannot find any relevant issues.
我已经简化我的查询到这一点:
I have simplified my query to this:
var test = from values in myTable.AsEnumerable()
select new valueSet
{
ID = values["ID"].ToString(),
Number = values["Number"].ToString(),
Name = this.getName(values["Number"].ToString()),
}
由于我运行该功能时的获得查询中的异常的的getName 我希望能够捕获异常,也该 编号的我目前是。事情是这样的:
Since I get an exception inside the query when running the function getName I want to be able to catch the exception and also which Number I am currently at. Something like this:
try
{
var test = from values in myTable.AsEnumerable()
select new valueSet
{
ID = values["ID"].ToString(),
Number = values["Number"].ToString(),
Name = this.getName(values["Number"].ToString()),
}
catch (Exception ex)
{
//I want to use "Number" here!
throw ex;
}
我意识到我宣布尝试里面我的测试变量,但能我为每一个LINQ循环存储当前号码?有什么建议么?
I am aware of that I declare my test-variable inside the try but can I for each "linq-loop" store the current Number? Any suggestions?
推荐答案
要实现这一点,你将不得不使用使用扩展方法和lambda表达式其他LINQ语法:
To achieve this, you will have to use the "other" LINQ syntax that uses extension methods and lambdas:
var test = myTable.AsEnumerable().Select(values =>
{
try
{
return new valueSet
{
ID = values["ID"].ToString(),
Number = values["Number"].ToString(),
Name = this.getName(values["Number"].ToString()),
};
}
catch(Exception ex)
{
throw new ApplicationException("cannot load number" + values["Number"].ToString());
}
});
这篇关于里面的Linq catch异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!