gpt4 book ai didi

c# - LINQ 延迟执行的微妙之处

转载 作者:太空宇宙 更新时间:2023-11-03 20:14:13 25 4
gpt4 key购买 nike

所有,我最近本地化了整个应用程序,我面临以下问题;我的应用程序中有以下 LINQ 查询

var ccsum = from a in dtSumGL2.AsEnumerable()
group Math.Abs(a.Field<double>(strpcPSPassBegCost)) by new
{
BaseCC = a.Field<string>(strpcBaseCC)
}
into g
select new
{
g.Key.BaseCC,
PSPassBegCost = g.Sum()
};

这是创建一个新对象 ccsum,我们用它来创建一个 DataTable 并随后填充一个 SQL Server 数据库。

问题是在 DataTable 中创建的每个新项目都带有列名 BaseCCPSPassBegCost,但这些名称并不匹配这些名称的德语版本。现在我的问题是:有没有办法做类似的事情:

var ccsum = from a in dtSumGL2.AsEnumerable()
group Math.Abs(a.Field<double>(strpcPSPassBegCost)) by new
{
BaseCC = a.Field<string>(strpcBaseCC)
}
into g
select new
{
g.Key.BaseCC as Resources.BaseCC,
PSPassBegCost = g.Sum() as Resources.PSPassBegCost
};

以便我可以根据本地化名称命名表?


编辑。从 ccsum 中获取 DataTable 的代码是

fooDt = Utils.LINQToDataTable(ccsum);

public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{

DataTable dtReturn = new DataTable();
PropertyInfo[] oProps = null;
if (varlist == null)
return dtReturn;

foreach (T rec in varlist)
{
// Use reflection to get property names, to create
// table, Only first time, others will follow.
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}

DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}

感谢您的宝贵时间。

另一种方法可能是将 ccsum 对象中的“列”重命名为后处理步骤,尽管 sumcc 的值直到它们被填充在运行时请求 - 还有其他想法吗?

最佳答案

创建将列索引映射到一些可读名称的类或枚举:

public static class SumGLColumn
{
public const int BaseCC = 0;
public const int PSPassBegCost = 1;
}

并使用列索引而不是列名来查询您的数据表:

var ccsum = from a in dtSumGL2.AsEnumerable()
group Math.Abs(a.Field<double>(SumGLColumn.PSPassBegCost))
by a.Field<string>(SumGLColumn.BaseCC) into g
select new {
BaseCCg = g.Key,
PSPassBegCost = g.Sum()
};

关于c# - LINQ 延迟执行的微妙之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17992391/

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