gpt4 book ai didi

c# - 在 C# 列表中如何选择所有列+几个自定义列,以便在每一行中所有列都是扁平的(不是嵌套的)?

转载 作者:行者123 更新时间:2023-11-30 13:07:00 32 4
gpt4 key购买 nike

我有一个简单的 List,它的每一行都有 50 列。我想返回所有 50 列 + 3 个自定义列 但我想让列表的每一行都像一个平面(非嵌套)对象。

示例:

var newList = list.Select(x => new 
{ x,
d.CustomColA = x.ColA+10,
d.CustomColB = x.ColB+30,
d.CustomColC = x.ColC+50
});

结果:它运行良好每个结果行就像一个嵌套对象:

var row = newList.FirstOrDefault();
row.x.ColA
row.x.ColB
row.x.ColC
.....
row.CustomColA
row.CustomColB
row.CustomColB

预期结果:

var row = newList.FirstOrDefault();
row.ColA
row.ColB
row.ColC
.....
row.CustomColA
row.CustomColB
row.CustomColB

我使用了dynamic 类型并编写了以下代码,但它没有返回预期的结果:

var newList = list.Select(x =>
{
dynamic d = x;
d.CustomColA = x.ColA+10;
d.CustomColB = x.ColB+30;
d.CustomColC = x.ColC+50;
return d;
//return x;
});

监视面板中的结果:'newList.FirstOrDefault()' 引发了类型为 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' 的异常


更新:

Attention: I wrote in my question that i have 50 columns and wrote anexample to show you i do not want name all the columns in the Select!(I know I can write name of all 53 column in a Select!) So that is not the correct answer.

Attention2: In the real project i have complicated custom columns but i wrote very simple example here to show what i want. Please write your flexible answers. Thank you.

最佳答案

所以您要做的基本上是映射一组属性。有用于此类事情的库,Automapper 是一个很好的库。但是,您也可以使用继承类中的反射构造函数自己完成此操作。看起来像这样:

假设:

  • 你的类有 50 列,叫做 Cols
  • 你可以继承Cols


public class CustomColumns : Cols
{
public int CustomColA {
get{
return this.ColA + 10;
}
}
public int CustomColB {
get{
return this.ColB + 30;
}
}
public int CustomColC {
get{
return this.ColC + 50;
}
}
public CustomColumns(Cols cols)
{
string[] localNames = this.GetType().GetMembers().Where(m => m.MemberType == MemberTypes.Property).Select(m => m.Name).ToArray();
string[] ctorNames = cols.GetType().GetMembers().Where(m => m.MemberType == MemberTypes.Property).Select(m => m.Name).ToArray();
string[] names = localNames.Intersect(ctorNames).ToArray();
foreach (string s in names)
{
PropertyInfo propSet = this.GetType().GetProperty(s);
PropertyInfo propGet = typeof(Cols).GetProperty(s);
propSet.SetValue(this, propGet.GetValue(cols, null));
}
}
}

这是在 dotnetfiddle 中工作的演示:https://dotnetfiddle.net/AKPYQD

关于c# - 在 C# 列表中如何选择所有列+几个自定义列,以便在每一行中所有列都是扁平的(不是嵌套的)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315232/

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