[英]How to move a subset of items in a list in c#?
我有以下清單:
List<string> l=new List<string()>{"a","b","c","d","1","2","3","4","a1","b2","c3","d4"};
我有oldIndex
、 size
和newIndex
。
假設上面的列表oldIndex = 4
, size = 4
, newIndex = 0
。
我想要的輸出列表是:
{"1","2","3","4","a","b","c","d","a1","b2","c3","d4"};
我找到的解決方案是(不適用於所有情況):
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);
}
}
有沒有更好的方法,也許使用 LINQ 或更好的方法,或者以上是唯一的方法?
我從這個鏈接找到了上面的答案。 這個問題的不同之處在於我想移動一個塊,而不僅僅是單個元素。
您可以為此使用以下內容:
List<string> removedRange = l.GetRange(oldIndex, size);
l.RemoveRange(oldIndex, size);
l.InsertRange(newIndex, removedRange);
有許多不同的方法可以做到這一點。
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;
移動:
var toMove = l.Skip(oldIndex).Take(size).ToList();
var newList = l.Take(oldIndex).ToList().Concat(l.Skip(oldIndex + size)).ToList();
newList.InsertRange(newIndex, toMove);
如果您能夠移動{"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));
...還有另一種方式(實際上可能是最簡單的閱讀方式):
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.