在两个列表之间交换bool值,C#

时间:2017-06-09 14:02:22

标签: c# list collections iteration

请帮助我找到一种方法来执行以下操作:

我有两个<img [src]="source" (mousedown)="activateTimer()" (mouseup)="deactivateTimer()">

第一个包含不同的bool值,我对第二个的长度和内容一无所知。我必须经历第一个List<bool>,如果我遇到真正的价值,我需要在第二个List<bool>中在第一个List<bool>中遇到的完全相同的位置写下它。

例如,第一个列表由false-false-true组成,这意味着我应该在第二个List<bool>的第三个位置写入true,第二个应该看起来像...... -..- true如果...位置上有什么东西我应该保留它,如果那里什么也没有,我应该把它放在那里。

2 个答案:

答案 0 :(得分:2)

据我所见,唯一(小)难度在于:Math.Min(list1.Count, list2.Count)

List<bool> list1 = new List<bool>() { true, false, true, false };
List<bool> list2 = new List<bool>() { false };

...

// Math.Min(list1.Count, list2.Count): ...I know nothing about the length
for (int i = 0; i < Math.Min(list1.Count, list2.Count); ++i)
  if (list1[i])      // ... if I meet a true value
    list2[i] = true; // I need to write it in the second ... at the exactly same position

测试:

 // [true]
 Console.Write("[" + string.Join(", ", list2) + "]");

修改:如果您想填充 list2 false,以确保所有true都在其索引处:

 for (int i = 0; i < list1.Count; ++i)
    if (list1[i]) {
      if (i >= list2.Count) // do we want padding?
        list2.AddRange(new bool[i - list2.Count + 1]);

      list2[i] = true;
    }

测试:

 // [true, false, true]
 Console.Write("[" + string.Join(", ", list2) + "]");

答案 1 :(得分:0)

var firstList = new List<bool> { false, false, true };
var secondList = new List<bool> { true };

for(int i =0; i < firstList.Count; i++)
{
    var currentItem = firstList[i];

    // If the item in the first list is true, then we need to insert it into the second list
    if(currentItem)
    {
        // If the second list is shorter than the actual index,
        // we insert missing elements so we can be able to insert the matching true in first list 
        // at the exact same position in second list.
        while(secondList.Count < i)
        {
            // Inserting false as you ask
            secondList.Add(false);
        }

        // Now the second list has at at least enough elements, 
        // we can insert true at the exact same location. 
        // Note that this will shift all other elements after that index
        secondList.Insert(i, currentItem);
    }
}

结果:

foreach(var item in secondList)
{
    Console.WriteLine(item);    
}

// true    <- already in the second list at the begining
// false   <- added by default because there was no element in 2nd position
// true    <- added because in the first list

请注意,如果您想要替换同一位置的现有值,则需要使用此代码(请注意条件中的 i + 1 和使用 setter indexer 和secondList:

while(secondList.Count < i+1)
{
    secondList.Add(false);
}

secondList[i] = currentItem;