Skip to content

Instantly share code, notes, and snippets.

@derans
Created March 12, 2012 06:12
Show Gist options
  • Save derans/2020194 to your computer and use it in GitHub Desktop.
Save derans/2020194 to your computer and use it in GitHub Desktop.
Move Items using LINQ
protected void moveItems(ListControl source, ListControl destination)
{
var getListItemsFrom = new Func<ListControl, List<ListItem>>
(x => x.Items.Cast<ListItem>().ToList());
var selectedItems = getListItemsFrom(source).Where(x => x.Selected);
var nonSelectedItems = getListItemsFrom(source).Where(x => !x.Selected);
var currentDestinationItems = getListItemsFrom(destination);
//Thanks Ryan for the .Except instead of the .Where(not)
currentDestinationItems.AddRange(selectedItems.Except(currentDestinationItems));
ReloadItemsFor(destination, /*with*/ currentDestinationItems);
ReloadItemsFor(source, /*with*/ nonSelectedItems);
destination.ClearSelection();
}
private void ReloadItemsFor(ListControl listControl, IEnumerable<ListItem> itemsToAdd)
{
listControl.Items.Clear();
listControl.Items.AddRange(itemsToAdd.OrderBy(x => x.Text).ToArray());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment