Home > OS >  Create a new List based on another two Lists C#
Create a new List based on another two Lists C#

Time:07-18

i'm trying to write a desktop app using c# .NET , but currently i'm stuck in the following problem:

Assume you have two Lists:

List1=[1,2,3,4]

List2=[1,4,1,3]
 

And i want a new list that is filled with "n" zeros between two consecutive elements of list1, been "n" the "i" element of list2, the new list should look like this:

List3=[1,0,2,0,0,0,0,3,0,4,0,0,0]
 

My Code:

  List<int> idID = new List<int>();
            idID.Add(1);
            idID.Add(2);
            idID.Add(3);
            idID.Add(4);
            List<int> Nevent = new List<int>();
            Nevent.Add(1);
            Nevent.Add(4);
            Nevent.Add(1);
            Nevent.Add(3);

            int total = Nevent.Count;



            for (int j = 0; j < total; j  )
            {
                for (int i = 1; i <= Nevent[j]; i  )
                {                
                    idID.Insert(i, 0);    //modify (____,0) of this line???
                }

            }


            string IDS = String.Join(",", idID);
            Console.WriteLine(IDS);

  

I think that i should change the part with idID.Insert(i, 0); and replace the i with some kind of sequence form like N0,N0 N1,N0 N1 N2,... been Ni the i element of list2 (that i name Nevent in the code) but i do not know how to do that.

How should I proceed? or there is a better way to achive what i want? Thank you in advance.

CodePudding user response:

If we assume the lists are the same length, you can make use of Zip to zip the 2 arrays together, and then a bit of LINQ to build up and select the resulting array

var result = idID.Zip(Nevent, 
                      (x,y) => new[]{ x }.Concat(Enumerable.Repeat(0,y)) )
                 .SelectMany(x => x);

result is

1,0,2,0,0,0,0,3,0,4,0,0,0

Live example: https://dotnetfiddle.net/PvtOVv

If you want/need to have result as a list just tag ToList() on the end

CodePudding user response:

Create new list, and treat idID and Nevent as input only. With LINQ we can use Enumerable.Repeat, otherwise we would have to use inner loop to add zeros.

using System.Linq;

...

List<int> result = new List<int>();

for (int j = 0; j < idID.Count; j  )
{
    result.Add(idID[j]);
    result.AddRange(Enumerable.Repeat(0, Nevent[j]));
}

CodePudding user response:

Another approach is to process the list backwards. Like this the inserted zeroes do not alter the indexes of elements to be processed.

var idID = new List<int> { 1, 2, 3, 4 };
var Nevent = new List<int> { 1, 4, 1, 3 };

for (int i = idID.Count - 1; i >= 0; i--) {
    for (int n = 0; n < Nevent[i]; n  ) {
        idID.Insert(i   1, 0);
    }
}

Console.WriteLine(String.Join(",", idID));

prints

1,0,2,0,0,0,0,3,0,4,0,0,0

CodePudding user response:

Add .ToList() with answer of @Jamiec

  • Related