[英]How to move a subset of items in a list in c#?
I have the following list:我有以下清单:
List<string> l=new List<string()>{"a","b","c","d","1","2","3","4","a1","b2","c3","d4"};
And I have oldIndex
, size
and newIndex
.我有
oldIndex
、 size
和newIndex
。
Let's say for the above list oldIndex = 4
, size = 4
, newIndex = 0
.假设上面的列表
oldIndex = 4
, size = 4
, newIndex = 0
。
The output list I would like is:我想要的输出列表是:
{"1","2","3","4","a","b","c","d","a1","b2","c3","d4"};
The solution I've found is(which is not working for all cases):我找到的解决方案是(不适用于所有情况):
for(int i=0;i<size;i++)
{
if(oldIndex<newIndex)
{
var x=l[oldIndex];
l.RemoveAt(oldIndex);
l.Insert(newIndex+size-1,x);
}
else
{
var x=l[oldIndex+i];
l.RemoveAt(oldIndex+i);
l.Insert(newIndex+i,x);
}
}
Is there any better way to this, perhaps using LINQ or something better, or is the above the only way to this?有没有更好的方法,也许使用 LINQ 或更好的方法,或者以上是唯一的方法?
I found the above answer from this link.我从这个链接找到了上面的答案。 The difference in this question is that I would like to move a block, and not just single element.
这个问题的不同之处在于我想移动一个块,而不仅仅是单个元素。
You can use the following for this:您可以为此使用以下内容:
List<string> removedRange = l.GetRange(oldIndex, size);
l.RemoveRange(oldIndex, size);
l.InsertRange(newIndex, removedRange);
There are many different ways to do this.有许多不同的方法可以做到这一点。
Raviraj Palvankar's answer is probably the simplest, but to complement it (and since you specifically mentioned linq), here are a couple of ( admittedly somewhat over-engineered ) alternatives. Raviraj Palvankar 的答案可能是最简单的,但为了补充它(并且因为您特别提到了 linq),这里有几个(诚然有些过度设计的)替代方案。
List<string> l = new List<string>{"a","b","c","d","1","2","3","4","a1","b2","c3","d4"};
var oldIndex = 4;
var size= 4;
var newIndex = 0;
To move:移动:
var toMove = l.Skip(oldIndex).Take(size).ToList();
var newList = l.Take(oldIndex).ToList().Concat(l.Skip(oldIndex + size)).ToList();
newList.InsertRange(newIndex, toMove);
If you're able to move the section {"a","b","c","d"}
instead (requires knowing a different new index, and does not require oldIndex
, since it will be 0), then the move-operation itself becomes easier:如果您能够移动
{"a","b","c","d"}
(需要知道不同的新索引,并且不需要oldIndex
,因为它将是 0),那么移动操作本身变得更容易:
var newIndex = 4; // Replace previous value which was 0
var size= 4; // Elements a - d
var newList = l.Skip(size).ToList();
newList.InsertRange(newIndex, l.Take(size));
...and yet another way (which may actually be the simplest to read ): ...还有另一种方式(实际上可能是最简单的阅读方式):
var oldIndex = 4;
var size= 4;
var toMove = l.Skip(oldIndex).Take(size).ToList();
var firstPart = l.Take(oldIndex);
var lastPart = l.Skip(oldIndex + size);
var combined = toMove.Concat(firstPart).Concat(lastPart);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.