Thursday, 15 October 2020

C# - LINQ - Using LINQ instead of Multiple Foreach Loops

 using System.Collections.Generic;

 namespace WorldCup

{

    public class Community

    {

        public List<Tournament> Tournaments = new List<Tournament>()

        {

            new Tournament { Rounds = new List<Round>()},

        };

    }

 

    public class Tournament

    {

        public List<Round> Rounds = new List<Round>()

        {

            new Round { Matches = new List<Match>()},

        };

    }

 

    public class Matches 

    {      

 

        public List<Round> Rounds = new List<Round>();

    }

 

    public class Round

    {

        public List<Match> Matches = new List<Match>();

    }

 

    public class Match

    {

        public Home home = new Home();

        public Away away = new Away();

 

        public class Home

        {

            int mParticipantId = 0;

            public int? ParticipantId

            {

                get { return mParticipantId; }

                set { value = mParticipantId ; }

            }

        }

 

        public class Away

        {

            int mParticipantId = 0;

            public int? ParticipantId

            {

                get { return mParticipantId; }

                set { value = mParticipantId; }

            }

        }

    }

}

 

MULTIPLE FOR LOOP

            var participantList1 = new List<int?>();

            var communities = new List<Community>();

 

            foreach (var community in communities)

            {

                foreach (var tournament in community.Tournaments)

                {

                    foreach (var round in tournament.Rounds)

                    {

                        foreach (var match in round.Matches)

                        {

                            if (match.home.ParticipantId.HasValue)

                            {

                                participantList1.Add(match.home.ParticipantId);

                            }

                            if (match.away.ParticipantId.HasValue)

                            {

                                participantList1.Add(match.away.ParticipantId);

                            }

                        }

 

                    }

                }

            }

 

LINQ Lamda Expression 

            var participantList = communities.SelectMany(c => c.Tournaments)

                                 .SelectMany(t => t.Rounds)

                                 .SelectMany(r => r.Matches)

                                 .Where(m => m.home.ParticipantId.HasValue ||

                                             m.home.ParticipantId.HasValue)

                                 .ToList();


No comments:

Post a Comment