Chuhukon, collection, Linq and SelectMany

Welcome to Koodr. Don't miss a snippet from Chuhukon and learn more about: collection, Linq and SelectMany . At Koodr you show what code you have got. Use your OpenID to login and start sharing your own collection snippets.

Chuhukon

Chuhukon

Jeroen Wijdeven
http://www.chuhukon.nl

Flatten the resulting sequence of a #collection by using #Linq #SelectMany.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chuhukon
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialze Teams ...

            #region Champions
            
            List<Team> ChampionTeams = new List<Team>();
            ChampionTeams.Add(new Team
            {
                Name = "Milan",
                Players = new string[] { "Seedorf", "Emanuelson" }
                
            });

            ChampionTeams.Add(new Team
            {
                Name = "Bayern",
                Players = new string [] { "Robben", "Ribery" }
                
            });

            ChampionTeams.Add(new Team
            {
                Name = "Barca",
                Players = new string [] { "Messi", "Villa" }
                
            });

            #endregion

            #region European League

            List<Team> OtherTeams = new List<Team>();
            OtherTeams.Add(new Team
            {
                Name = "PSV",
                Players = new string[] { "Toivonen", "Bouma" }

            });
            OtherTeams.Add(new Team
            {
                Name = "Man. City",
                Players = new string[] { "De Jong", "Silva" }

            });

            OtherTeams.Add(new Team
            {
                Name = "Valencia",
                Players = new string[] { "Jonas", "Topal" }

            });

            #endregion

            //Initialize Leauges

            List<League> Leagues = new List<League>();
            Leagues.Add(new League
            {
                Name = "Champions League",
                Teams = ChampionTeams
            });

            Leagues.Add(new League
            {
                Name = "UEFA Europa League",
                Teams = OtherTeams
            });

            //Use Linq to retrieve a collection of all players, playing in one of the UEFA Leagues
            
            var result = Leagues.SelectMany(l => l.Teams.SelectMany(t => t.Players));

            foreach (var player in result)
            {
                Console.WriteLine(player);
            }

        }
    }

    public class Team
    {
        public string Name { get; set; }
        public string[] Players { get; set; }
    }

    public class League
    {
        public string Name { get; set; }
        public IEnumerable<Team> Teams { get; set; }
    }
}