假設您有一個班級串列,并且您想從其他串列中添加其他資訊。如何創建 2 個或更多物件實體并從另一個 List 集合中插入資料?請參閱下面的示例代碼:
using System;
using System.Collections.Generic;
class Person
{
public string Fname {get; set;}
public string Lname {get; set;}
public int age {get; set;}
}
class MainTest {
static void Main() {
//Console.WriteLine();
List<string> FNames = new List<string> { "Ben", "John" };
List<string> LNames = new List<string> { "Park", "Wilson" };
List<int> Ages = new List<int> { 20,25};
List<Person> PersonsL = new List<Person>();
//Person = new Person();
for (int i=0;i<2;i )
{
Person = new Person();
foreach (Person datas in PersonsL)
{
datas.Fname = FNames[i];
datas.Lname = LNames[i];
datas.age = Ages[i];
}
}
}
}
uj5u.com熱心網友回復:
你不需要迭代PersonL,因為這個串列實際上沒有元素。只需致電PersonL.Add:
using System;
using System.Collections.Generic;
class Person
{
public string Fname {get; set;}
public string Lname {get; set;}
public int age {get; set;}
}
class MainTest
{
static void Main() {
//Console.WriteLine();
List<string> FNames = new List<string> { "Ben", "John" };
List<string> LNames = new List<string> { "Park", "Wilson" };
List<int> Ages = new List<int> { 20,25};
List<Person> PersonsL = new List<Person>();
for (int i=0;i<2;i )
{
var p = new Person();
p.Fname = FNames[i];
p.Lname = LNames[i];
p.age = Ages[i];
PersonL.Add(p)
}
}
}
或者,您也可以使用物件初始化器:
PersonL.Add(new Person { Fname = FNames[i], Lname = LNames[i], age = Ages[i] });
uj5u.com熱心網友回復:
你可以使用 Zip linq
List<Person> PersonsL = FNames.Zip(LNames, Ages)
.Select(fn => new Person {Fname=fn.First,Lname=fn.Second,age=fn.Third} ).ToList();
如果需要,可以將其添加到另一個串列
anotherList.AddRange(PersonL);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415679.html
標籤:
上一篇:IL切換指令
