从多个数组填充List <t> </t>

时间:2013-01-24 16:24:02

标签: c# arrays list populate

所以,基本上我需要用数组而不是手工填充当前列表:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            List<People> people = new List<People>()
            {
                new People{Name="John",Age=21,Email="john@abc.com"}
                new People{Name="Tom",Age=30,Email="tom@abc.com"}
            };
        }
    }

到目前为止,我上课的人都喜欢这样:

    class People
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Email { get; set; }
    }

我想使用数组,从类People到MainWindow类。类似的东西:

    class People
    {
        public string[] Name =
        {
            "John",
            "Tom",
        };
        public int[] Age =
        {
            "21",
            "30",
        }
        ...
    }

我似乎无法弄清楚如何使用这些数组来填充此列表。提前感谢您的时间。

3 个答案:

答案 0 :(得分:2)

int c = people.Name.Count;

Enumerable.Range(0,c).Select(i => new People(){Name = people.Name[i], Age = people.Age[i], ...});

您需要确保所有阵列都具有相同的大小。

如果将“数据”设置为静态,那会更好。

我们可以int c = Math.Min(people.Name.Count, people.Age.Count, ...);做更好的“symetry”

答案 1 :(得分:0)

其中一个Select重载index作为参数

var names = new[]{ "John", "Tom" };
var ages  = new[]{ 21, 30, };
var mails = new[]{ "mail1", "mail2", };

names.Select((name, index) => 
       new People{
       Name = name, 
       Age = ages[index], 
       Email = mails[index]})
     .Dump();

打印:

Name Age Email 
John 21  mail1 
Tom  30  mail2 

答案 2 :(得分:0)

如果要预先填充集合

,有很多方法可以做到这一点
public static class PeopleListFactory
{
   public static IEnumerable<People> Content(int someindicator)
   {
      List<People> result = new List<People>();
      switch (someIndicator)
      {      
        case 0: // fill it in here with and from whatever you like.
        break;
      }
      return result;
   }
}

然后在你的主要表格中 它只是

列出人物=新名单(PeopleListFactory.Content(0));