在两个列表c#linq的索引之后交换数据

时间:2015-07-26 00:00:04

标签: c# linq list

所以我有两个字节列表,我想在给定索引之后交换它们的数据。

所以我有这两个列表

---- 0 --- 1 ----- 2 ----- 3 ----索引

#### **** #### #### -ListA

#### #### **** #### **** -ListB

我想说如果索引是这样的2交换数据

#### **** **** #### ****

#### #### #### ####

我对linq不太熟悉,也许有一种快速的方法可以用它来做。

谢谢,

2 个答案:

答案 0 :(得分:2)

这可以在没有Linq的情况下完成。使用List.GetRange()List.RemoveRange()和& List.AddRange()你可以执行你正在寻找的交换,并且很快。

List<string> listA = new List<string>
{
    "####", 
    "****", 
    "####", 
    "####"
};

List<string> listB = new List<string>
{
    "####",
    "####",
    "****",
    "####",
    "****"
};

Console.WriteLine("Before: ");
Console.WriteLine("List A: {0}", String.Join(", ", listA));
Console.WriteLine("List B: {0}", String.Join(", ", listB));
Console.WriteLine();

SwapAfterIndex(listA, listB, 2);

Console.WriteLine("After: ");
Console.WriteLine("List A: {0}", String.Join(", ", listA));
Console.WriteLine("List B: {0}", String.Join(", ", listB));

SwapAfterIndex()看起来像:

public static void SwapAfterIndex(List<string> listA, List<string> listB, int index)
{
    if (index < 0)
    {
        return;
    }

    List<string> temp = null;
    if (index < listA.Count)
    {
        temp = listA.GetRange(index, listA.Count - index);
        listA.RemoveRange(index, listA.Count - index);
    }

    if (index < listB.Count)
    {
        listA.AddRange(listB.GetRange(index, listB.Count - index));
        listB.RemoveRange(index, listB.Count - index);
    }

    if (temp != null)
    {
        listB.AddRange(temp);
    }
}

结果:

Before:
List A: ####, ****, ####, ####
List B: ####, ####, ****, ####, ****

After:
List A: ####, ****, ****, ####, ****
List B: ####, ####, ####, ####

答案 1 :(得分:0)

我认为2 List没有交换方法。您可以使用以下代码实现相同的功能。

public static void Swap2List(List<byte> firstList, List<byte> secondList, int index)
  {
       // TODO : Error handling not done.  
        for(int i = index; i < firstList.Length ; i++)
       {
         var temp = firstList[i];
         firstList[index] = secondList[i];
         secondList[i] = temp;
       }
    }