Search code examples
c#arrayslistpopulate

Populating List<T> from multiple arrays


So, basically I need to populate this current list with arrays instead of by hand:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            List<People> people = new List<People>()
            {
                new People{Name="John",Age=21,Email="[email protected]"}
                new People{Name="Tom",Age=30,Email="[email protected]"}
            };
        }
    }

So far I have class People like this:

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

And I would like to use arrays instead, from class People into class MainWindow. Something like:

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

I just can't seem to figure out how to pupulate this list using these arrays. Thank you in advance for your time.


Solution

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

    You need be sure that all arrays have the same size.

    And it would be better if you set your "data" as static.

    we can do int c = Math.Min(people.Name.Count, people.Age.Count, ...); for a better "symetry"