【问题标题】:Adding list items to another list repeatedly for a certain number of times C# UWP将列表项重复添加到另一个列表一定次数C# UWP
【发布时间】:2018-04-08 03:32:46
【问题描述】:

我有两个列表。第一个列表是空的,但必须填充一定次数。第二个列表包含已知数量的元素,这些元素必须循环分配给第一个列表,直到第一个列表已满。

类似这样的:

List<Product> productList1 = new List<Product>(); // previously populated list. 
List<Product> productList2 = new List<Product>();

for (int i = 0; i < productList1.Count; i++)
{
    Product _product = new Product;
    _product.ProductName = productList1[i].ProductName;
    productList2.Add(_product);
}

int n = productList2.Count;

List<Product> productList3 = new List<Product>;

for (int f = 0; f < n; f++)
{
    for (int i = 0; i < 60; i++)
    {
        productList3.Add(productList2[f];
    }
}

// repeat 'f' loop until i arrives at 60

例如。 List2.Count = 4,用 List2 Products 交替填充 List3,直到 List3 达到总共 60 个 Products。

productList2: Product1, Product2, Product3, Product4.
productList3: Product1, Product2, Product3, Product4, Product1, Product2, Product3, Product4, Product1, Product2, Product3, Product4, and so on until reached 60 records. 

【问题讨论】:

    标签: c#


    【解决方案1】:

    如果我正确理解了您的问题,如果您的原始列表有 n 个元素,在新列表的 n+1 位置,您需要添加原始列表的第一个元素,在 n+2 位置,第二个, 在 2n + 1 上再次第一次等等。

    所以你可以试试这个

    int n = 60; //could be any number
    int count = originalList.Count;
    
    for (int i = 0; i < n; i++)
    {
        newList.Add(originalList[i % count]); //the remainder of the division
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 2019-09-22
      • 2022-08-02
      相关资源
      最近更新 更多