gpt4 book ai didi

c# - 使用检查 c# 合并两个数据表

转载 作者:行者123 更新时间:2023-11-30 23:19:06 27 4
gpt4 key购买 nike

我有如下两个数据表,

dtOrigin
RowId Stk ProdName
2 245 ABC
4 144 XYZ
5 122 ADE


dt1
RowId Stk
2 2
4 7

我需要合并这两个数据表以产生以下结果,基本上如果 rowid 存在于 dt1 中,需要从 dtOrigin 中减去其库存数量dt新建

RowId Stk           ProdName
2 243(245-2) ABC
4 137(144-7) XYZ
5 122 ADE

我可以用循环来做到这一点,但是无论如何也可以不用循环来做到这一点谢谢

                    var JoinResult = (from p in dt1.AsEnumerable()
join t in dt2.AsEnumerable()
on p.Field<string>("RowID") equals t.Field<string>("RowID")
into joinedtables from stuff in joinedtables.DefaultIfEmpty()
select new
{
----------------,
----------------,
Stock = p.Field<Int32>("Stk") - stuff.Field<Int32>("Stk")
}

抛出异常。你能纠正一下吗?


下面是我使用的代码

    var JoinResult = (from p in dt.AsEnumerable()
join t in dt2.AsEnumerable()
on p.Field<string>("RowID") equals t.Field<string>("RowID")
into joinedtables from stuff in joinedtables.DefaultIfEmpty()
select new
{
RowID = p.Field<string>("RowID"),
ProdName = p.Field<string>("ProdName"),
STK = p.Field<Int32>("STK") - stuff?.Field<Int32>("STK") ?? 0
}

dtable = LINQResultToDataTable(JoinResult);




public static DataTable LINQResultToDataTable<T>(IEnumerable<T> Linqlist)
{
DataTable dt = new DataTable();


PropertyInfo[] columns = null;

if (Linqlist == null) return dt;

foreach (T Record in Linqlist)
{

if (columns == null)
{
columns = ((Type)Record.GetType()).GetProperties();
foreach (PropertyInfo GetProperty in columns)
{
Type IcolType = GetProperty.PropertyType;

if ((IcolType.IsGenericType) && (IcolType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
IcolType = IcolType.GetGenericArguments()[0];
}

dt.Columns.Add(new DataColumn(GetProperty.Name, IcolType));
}
}

DataRow dr = dt.NewRow();

foreach (PropertyInfo p in columns)
{
dr[p.Name] = p.GetValue(Record, null) == null ? DBNull.Value : p.GetValue
(Record, null);
}

dt.Rows.Add(dr);
}
return dt;
}

最佳答案

试试这个:

var JoinResult = 
...
select new {
...
Stock = p.Field<Int32>("Stk") - (stuff?.Field<Int32>("Stk") ?? 0)
};

我猜测当第二个数据表中没有匹配的记录时,stuff 将是 null,从而在尝试时导致 NullReferenceException读取该行的值。这个表达式:

stuff?.Field<Int32>("Stk")

表示“如果 stuffnull,则整个表达式的计算结果应为 null,否则应返回字段中的值。 "

这还不够;因为你不能从其他东西中减去 null。它需要传递给 ?? 运算符:

stuff?.Field<Int32>("Stk") ?? 0

这意味着如果左侧不是 null 则使用该值,否则使用 0。

关于c# - 使用检查 c# 合并两个数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40459629/

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