Reorder objects based on provided enumerable order This code feels like it goes through too many conversions to accomplish my goal:


  based on an IEnumerable of ids get those objects from a data store and
  set their DisplayOrder property to the position of the associated
  id.


Is there a more elegant solution that I'm missing?

public void ReorderElements(IEnumerable&lt;int&gt; elementSks)
{
    var elementsToReorder = GetSession().QueryOver&lt;DocumentElement&gt;()
        .WhereRestrictionOn(de =&gt; de.DocumentElementSk).IsIn(elementSks.ToArray()).List();

    var elementOrder = elementSks.Select((sk, i) =&gt; new { Sk = sk, Order = i })
        .ToDictionary(p =&gt; p.Sk, p =&gt; p.Order);

    elementsToReorder.ToList()
        .ForEach(e =&gt; e.DisplayOrder = elementOrder[e.DocumentElementSk]);

    this.Save(elementsToReorder);
}
If the list on input is going to be short, or if performance doesn't matter to you, you can simplify the code by using IndexOf() instead of the dictionary:

public void ReorderElements(IEnumerable&lt;int&gt; elementSks)
{
    var elementsToReorder = GetSession().QueryOver&lt;DocumentElement&gt;()
        .WhereRestrictionOn(de =&gt; de.DocumentElementSk).IsIn(elementSks.ToArray()).List();

    var elementOrder = elementSks.ToList();

    foreach(var element in elementsToReorder)
         element.DisplayOrder = elementOrder.IndexOf(element.DocumentElementSk);

    this.Save(elementsToReorder);
}