c# - 如何复制两个相似的列表?
问题描述
我有两个清单。只有一个字段差异。如何彼此填写列表。
[Serializable()]
public class Lst1
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
}
[Serializable()]
public class Lst2
{
public string filed1 { get; set; }
public Int16 filed2 { get; set; }
.
.
.
public Boolean filed100 { get; set; }
public string filed101 { get; set; }
}
List<Lst1> Lst1_ = new List<Lst1>();
List<Lst2> Lst2_ = new List<Lst2>();
我从文件中填写清单。然后,我需要从列表一中填写列表二,有很多字段并且我不想使用 foreach 循环。
应该记住,我之前的课程已经构建并序列化并存储在一个文件中。现在我需要将之前的信息转移到第二类结构中。
我不想使用这个循环!
foreach (var t in Lst1_)
{
Lst2_.Add(new lst2
{
filed1 = t.filed1,
filed2 = t.filed2,
.
.
.
filed100 = t.filed100,
filed101 = "kk"
}
}
解决方案
这是你想要的吗?
class Lst1
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
}
class Lst2
{
public string filed1 { get; set; }
public string filed2 { get; set; }
public string filed3 { get; set; }
public string filed4 { get; set; }
public string filed5 { get; set; }
public string filed6 { get; set; }
}
void CopyData()
{
// test data
List<Lst1> Lst1_ = new List<Lst1>()
{
new Lst1()
{
filed1 = "1",
filed2 = "2",
filed3 = "3",
filed4 = "4",
filed5 = "5",
},
new Lst1()
{
filed1 = "6",
filed2 = "7",
filed3 = "8",
filed4 = "9",
filed5 = "10",
},
};
List<Lst2> Lst2_ = new List<Lst2>();
foreach (var item in Lst1_)
{
Type type1 = item.GetType();
PropertyInfo[] properties1 = type1.GetProperties();
var current = new Lst2();
Type type2 = current.GetType();
PropertyInfo[] properties2 = type2.GetProperties();
int k = 0;
foreach (PropertyInfo property in properties1)
{
var value = property.GetValue(item, null);
int n;
bool isNumeric = int.TryParse(value.ToString(), out n);
if (!isNumeric)
value = "Your desired value";
properties2[k].SetValue(current, value);
k++;
}
Lst2_.Add(current);
}
}
它将列表 1 中的所有内容复制到列表 2。
推荐阅读
- c# - 如何在 C# 中创建按需 DynamoDB 表?
- android - Ionic - Android 10+ 上的文本输入未回显
- docker - docker-compose python:无法打开文件'./main.py':[Errno 2]没有这样的文件或目录
- jquery - 即使我使用 Jquery 刷新或重新加载页面,如何在网页上保留来自输入标签的数据
- javascript - Discord.js Bot 赠品命令:embedSent.reactions.get 不是函数
- cluster-analysis - 如何使用 NS2 使用 TCL 脚本中的剩余能量值?
- excel - 刷新数据透视表
- javascript - 如何在 Electron Js 项目中使用母版页
- python - 如何在python中将标题添加到散景仪表板?
- android - 在 ANDROID 中使用 AsyncTask() 启动 AlertDialog 时如何避免应用程序崩溃?