gpt4 book ai didi

c# - LINQ(无法将 'System.Double' 类型的对象转换为 'System.String' 类型。)

转载 作者:太空宇宙 更新时间:2023-11-03 17:54:10 26 4
gpt4 key购买 nike

我在使用 LINQ 概念时遇到问题。
下面我比较两个数据表,一个由数据库填充,另一个由 excel 文件填充。

问题是当我在两个“tempdt”之间应用连接时包含双值,这会导致转换对象的错误。
我无法将返回类型从字符串更改为 double ,因为它将来可能是任何数据类型,因为目前它是 double 的,将来可能是字母数字。

    var commonRows = from r1 in dt.AsEnumerable()
join r2 in tempdt.AsEnumerable()
on r1.Field<string>(0) equals r2.Field<string>(4)
select r2;
if (commonRows.Any())
{
abcdefgh = commonRows.Count();
dt123 = commonRows.CopyToDataTable();
// ring the ghanta of gutlu
}

Exception: Unable to cast object of type 'System.Double' to type 'System.String'.

最佳答案

这是我认为您的问题所在:

from r1 in dt.AsEnumerable()
join r2 in tempdt.AsEnumerable() on
r1.Field<string>(0) //<-- this may not be string
equals
r2.Field<string>(4) //<-- this may not be string
select r2;

您可以做的是将其视为对象:
from r1 in dt.AsEnumerable()
join r2 in tempdt.AsEnumerable() on
(string.Empty + r1.Field<object>(0)) <-- Edited by Andreas X
equals
(string.Empty + r2.Field<object>(4)) <-- Edited by Andreas X
select r2;

您应该做的是确保您的索引号(0 和 4)指向相同的类型。

编辑:当询问 tostring 值时,我通常使用旧的 ASP 技巧来避免空指针。

关于c# - LINQ(无法将 'System.Double' 类型的对象转换为 'System.String' 类型。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16141932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com