1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| /******************************************************************************
Online C# Compiler.
Code, Compile, Run and Debug C# program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
using System;
using System.Collections.Generic;
class HelloWorld {
class Component {
public string id { get; set; }
public int order { get; set; }
}
static void print_mylist(List<Component> mylist) {
mylist.ForEach(comp => Console.WriteLine("{0},{1}", comp.id, comp.order));
Console.WriteLine();
}
static void Main()
{
var mylist= new List<Component> {
new Component() {id="comp1", order=1}
, new Component() {id="comp2", order=2}
, new Component() {id="comp3", order=3}
};
var comp_id= "comp1";
var new_order= 3;
print_mylist(mylist);
//=================================================================
var tmplist= new List<Component>(mylist); //protect the original list against invalidation
var index_of_comp= tmplist.FindIndex(c => c.id.Equals(comp_id));
var comp= tmplist[index_of_comp];
tmplist.RemoveAt(index_of_comp);
var new_index_of_comp= new_order-1;
comp.order= new_order;
tmplist.Insert(new_index_of_comp, comp);
var start= Math.Min(index_of_comp, new_index_of_comp);
var end= Math.Max(index_of_comp, new_index_of_comp);
for (int i= start; i <= end; i++) {
tmplist[i].order= i+1;
}
mylist= tmplist;
//=================================================================
print_mylist(mylist);
}
} |
Partager