Change the order of line item positions

I have a Request object that contains a list of approvers. The approver has a name and place of approval.

  • Matthew
  • Mark
  • Luke
  • John

Ultimately, the request will go through this chain, starting with Matthew and ending at John.

I need to be able to reorder them by adding and removing, as described below.

The approver may be -

Added to a specific position - i.e. Add Peter to position 3, in which case the new order will be

  • Matthew
  • Mark
  • Peter
  • Luke
  • John

Delete - i.e. Unmark, in this case, the new order

  • Matthew
  • Luke
  • John

Edited - i.e. you can change John’s position by 1, in which case a new order

  • John
  • Matthew
  • Mark
  • Luke

I came up with a number of solutions, however none of them are particularly elegant.

Any help would be greatly appreciated

+5
2

, ? List<T>, , , , , . "" /.

.

LinkedList<T> - " ", " " "" , LinkedListNode<T>, . , " 3" - , 3 ( 2, ). " ", .

+5

- , , - ( ). / .

List<T> ? Add() , Insert() Remove() . -, Remove() Insert() ?

( ):

using System;
using System.Collections.ObjectModel;
using System.Linq;

// I only added this to use a lazier "collection initializer" below,
// which needs an Add(string) method...
class ApproverCollection : Collection<Approver> {
    public void Add(string name) { Add(new Approver(name)); }
}
class Request {
    public Request() { Approvers = new ApproverCollection(); }
    public ApproverCollection Approvers { get; private set; }
}
class Approver {
    public Approver(string name) { Name = name; }
    public string Name { get; set; }
}
static class Program {
    static void Main() {
        Request req = new Request {
            Approvers = {"Mathew", "Mark", "Luke", "John"}
        };
        req.ShowState("Initial");
        req.Approvers.Insert(2, new Approver("Peter"));
        req.ShowState("Inserted Peter");
        Approver mark = req.Approvers.Single(x => x.Name == "Mark");
        req.Approvers.Remove(mark);
        req.ShowState("Removed Mark");
        Approver john = req.Approvers.Single(x => x.Name == "John");
        req.Approvers.Remove(john);
        req.Approvers.Insert(0, john);
        req.ShowState("Moved John");
    }
    static void ShowState(this Request request, string caption) {
        Console.WriteLine();
        Console.WriteLine(caption);
        int pos = 1;
        foreach(Approver a in request.Approvers) {
            Console.WriteLine("{0}: {1}", pos++, a.Name);
        }
    }
}
+4

All Articles