轻松更改列表后的第n项

本文关键字:列表 | 更新日期: 2023-09-27 18:08:33

我得到了一个列表:var x = new List<string>(){"a","b","c"}

我正在寻找一个非常简单的方法来改变a后的所有项目例子:

var x = new List<string>(){"a","b","c"}
var y = new List<string>(){"d","e","f"}
x.addAfterFirst(y);

result x= "a","d","e","f"

我知道' x.Skip(1)'可以返回给我信息。我需要设置它

轻松更改列表后的第n项

您可以使用Take扩展方法从x中获取第一个n项,并使用concat扩展方法将它们与y连接:

List<string> x = new List<string> { "a", "b", "c" };
List<string> y = new List<string> { "d", "e", "f" };
int n = 1;
List<string> result = x.Take(n).Concat(y).ToList();
// result == { "a", "d", "e", "f" }

如果您想就地修改x而不是创建一个新列表,您可以使用RemoveRange方法来删除第一个n项之后的所有项,并使用AddRange方法将y附加到x:

List<string> x = new List<string> { "a", "b", "c" };
List<string> y = new List<string> { "d", "e", "f" };
int n = 1;
x.RemoveRange(n, x.Count - n);
x.AddRange(y);
// x == { "a", "d", "e", "f" }

Make use InsertRange will do you task

var x = new list<string>(){"a","b","c"}
var y = new list<string>(){"d","e","f"}
x.InsertRange(2,y);

编辑

现在如果你想删除元素

var x = new list<string>(){"a","b","c"};
int xlength = x.Count() - 1;
var y = new list<string>(){"d","e","f"};
int ylength = y.Count() - 1;
x.InsertRange(2,y);
x.RemoveRang( 2 + ylength, xlength- 2);

您的结果与完整描述不匹配

您要插入或替换

您是需要修改现有集合还是可以接受新的集合?

所有示例都使用以下初始化

var insertIndex=1;
var x = new List<string>(){"a","b","c"};
var y = new List<string>(){"d","e","f"}; 

新集合替换

var result=x.Take(insertIndex).Concat(y).ToList();

New Collection Insert

var result=x.Take(insertIndex).Concat(y).Concat(x.Skip(insertIndex)).ToList();

修改集合

x.RemoveRange(insertIndex,x.Count-insertIndex);
x.AddRange(y);

Modify Collection Insert

x.InsertRange(insertIndex,y);

非linq扩展方式:

int i;
for (i=0;i < y.Count;i++) 
{
     if (i+1 < x.Count)
         x[i+1] = y[i];
     else
         x.Add(y[i]); 
 }
 //If you dont want trailing elements to remain in x
 for (;i < x.Count;i++)
     x.RemoveAt(i);