user6512053
user6512053

Reputation:

C# - Joining two lists into one list of paired values

I have two lists that i am trying to join into one list on my application, as shown below -

PlatformIds with ids of 1 - 10. Percentages with values of 10 - 100. these lists are already ordered.

PlatformPercentages, this is where i want to join the above lists. This is a list of PlatformPercentages (List<PlatformPercentage>) which i have created which takes int PlatformId and double Percentage.

PlatformPercentages should contain the list information together, like so -

1: 10
2: 20
3: 30 

how can i do this?

all help appreciated!

ive tried nested foreach loops but it didnt work correctly.

var platformPercentages = new List<PlatformPercentage>();
foreach (var platformId in platformIds)
{
    foreach (var percentage in percentages)
    {
        var platformPercentage = new PlatformPercentage
        {
            PlatformId = platformId,
            Percentage = percentage,
        };
        platformPercentages.Add(platformPercentage);
    }
}

Upvotes: 0

Views: 104

Answers (3)

Guilhem Prev
Guilhem Prev

Reputation: 979

You can use Linq to do it in a simple line with the Zip function :

var platformIds = new List<int> { 1, 2, 3 };
var percentages = new List<int> { 10, 20, 30 };
var platformPercentages = platformIds.Zip(percentages, (id, pourcent) => new PlatformPercentage { PlatformId = id, Percentage = pourcent }).ToList();

Upvotes: 4

It&#39;s a trap
It&#39;s a trap

Reputation: 1353

Use a single for loop like this

for (int i = 0; i < platformIds.Count; i++)
        {
            platformPercentages.Add(new PlatformPercentage { Percentage = percentage[i], PlatformId = platformIds[i] });
        }

Upvotes: 0

Steven Teow
Steven Teow

Reputation: 21

I assume both platformIds list and percentages list are equally 10 records.

for(var i=0; i<platformIds.Count; i++){
        platformPercentages.Add(new PlatformPercentage{
                                      PlatformId = platformIds[i],
                                      Percentage = percentages[i],
                                 });
}

Upvotes: 0

Related Questions