【发布时间】:2011-01-25 16:40:37
【问题描述】:
我在尝试使用 LINQ 调用字符串操作方法时遇到了令人沮丧的问题。我现在做了很多搜索,并尝试了各种方法来让下面标记为“FAILS”的行正常工作。它当前会引发异常。
我尝试过的一些事情:
a) 最初连接键的创建是在同一个查询中,没有改变任何东西
b) 将非字符串字段转换为字符串(与 .ToString 一起工作的另一整罐工作在 linq 中不起作用。尝试了 String.Concat 和 String.Format,在某些情况下可以正常工作,但在您尝试参考时却不行该值稍后)
c) 使用 concat etc 而不是 '+' 将事物连接在一起。
如您所见,将字符串附加到非字符串似乎相当宽容,但在调用该方法时不是。
有很多行,所以我不希望将数据转换为列表/数组等,但如果这是唯一的选择,那么任何建议都会受到赞赏。
非常感谢! - 标记
var vouchers = from v in db.Vouchers
select new
{
v.Amount,
v.Due_Date,
v.Invoice_Date,
v.PO_CC,
v.Vendor_No_,
v.Invoice_No_,
invoiceNumeric = MFUtil.StripNonNumeric(v.Invoice_No_)
};
var keyedvouchers = from vv in vouchers
select new
{
thekey = vv.Vendor_No_ + "Test", // works with normal string
thekey2 = vv.Amount + "Test", // works with decimal
thekey3 = vv.Invoice_Date + "Test", // works with date
thekey4 = vv.invoiceNumeric, // works
thekey5 = vv.invoiceNumeric + "Test" // FAILS
};
-- 去除字符的方法---
public static string StripNonNumeric(string str)
{
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
// only append if its withing the acceptable boundaries
// strip special chars: if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') | || (c >= 'a' && c <= 'z') | c == '.' || c == '_')
// strip any nonnumeric chars
if (c >= '0' && c <= '9')
{
sb.Append(c);
}
}
return sb.ToString();
}
-- 异常消息--
System.InvalidOperationException 未被用户代码处理
Message=Could not translate expression 'Table(Voucher).Select(v => new f__AnonymousType07(Amount = v.Amount, Due_Date = v.Due_Date, Invoice_Date = v.Invoice_Date, PO_CC = v.PO_CC, Vendor_No_ = v.Vendor_No_, Invoice_No_ = v.Invoice_No_, invoiceNumeric = StripNonNumeric(v.Invoice_No_))).Select(vv => new <>f__AnonymousType15(thekey = (vv.Vendor_No_ + "Test"), thekey2 = (Convert(vv.Amount) + "Test "), thekey3 = (Convert(vv.Invoice_Date) + "Test"), thekey4 = vv.invoiceNumeric, thekey5 = (vv.invoiceNumeric + "Test")))' 转换为 SQL 并且无法将其视为本地表达式。
【问题讨论】:
标签: c# linq linq-to-sql