C# 将列表项复制到对象数组
本文关键字:对象 数组 复制 列表 | 更新日期: 2023-09-27 18:31:52
我有一个使用 EF6.0 从存储过程创建的列表
我还创建了 3 个类
public class Resas
{
public string todo{ get; set; }
public string prop { get; set; }
public string Code { get; set; }
public string statusCode { get; set; }
public string checkin { get; set; }
public string checkout { get; set; }
public List<profiles> profiles { get; set; }
}
public class profiles
{
public string action { get; set; }
public string id { get; set; }
public string profileType { get; set; }
public string title { get; set; }
public string firstName { get; set; }
public string middleName { get; set; }
public string lastName { get; set; }
public List<emailAddresses> emailAdresses { get; set; }
}
public class emailAddresses
{
public string emailAddress { get; set; }
public string emailAddress2 { get; set; }
}
我正在列表中做一个for循环,我需要获取某些列并将其放入数组中(为了简单起见,我将放置两个)
myEntities db = new myEntities();
List<rev_Result> revList = new List<rev_Result>();
revList.Clear();
revList = db.rev().ToList();
for (int i = 0; i < revList.Count(); i++)
{
Resas resas = new Resas();
profiles[] profiles = new profiles[1];
resas.todo = revList[i].todo;
resas.profiles[0].lastName = revList[i].lastName;
}
我不熟悉 C#,正如你从上面的 psedo 代码中看到的那样。
我无法弄清楚如何向 Resas 提供数据,然后用数据为其配置文件提供数据,然后移动到下一个 Resas 条目。
任何帮助表示赞赏。
使用 Linq 这相当简单:
Resas resas = new Resas();
resas.profiles = revList
.Select(x => new profiles() { action = x.todo, lastName = x.lastName })
.ToList();
这里发生的事情是:你遍历 revList 中的每个条目并获取你想要的数据结构(这就是Select
正在做的事情)。 x
是指循环中的当前条目,而箭头右侧的内容是您的"输出":profiles
类的新实例,并相应地分配了成员。然后将所有这些的结果转换为列表(在ToList()
之前,将其视为创建列表的配方)并分配给resas.profiles
。
顺便说一下,关于约定的词:通常,在 C# 中,您会为类指定一个以大写字母开头的名称。此外,您的profiles
类似乎只包含一个配置文件的数据,因此可能会Profile
更好的名称。这也使您的数据结构更加清晰,因为List<profiles>
似乎是配置文件列表的列表 - 但事实并非如此,是吗?
此外,成员通常也以大写字母开头,因此不是action
,lastName
,而是:Action
和LastName
。
你可以试试 Linq。这是应该解决您的问题的代码,但Resas
类没有action
属性:
List<Resas> ls = revList.Select(x => new Resas() {
action = x.todo,
profiles = new List<profiles>() {
new profiles { lastName = x.lastName }
}
).ToList();
如果需要使用action property of in
配置文件的类:
List<Resas> ls = revList.Select(x => new Resas() {
profiles = new List<profiles>() {
new profiles {
action = x.todo,
lastName = x.lastName
}
}
).ToList();