I have a large list of customers. Below is some sample data
Id Name Age PriorityLevel
1 Bill 50 1
2 Adam 40 2
3 Cory 60 3
4 Edgar 20 4
I want to swap the items in this list, so have used this code
public static List<T> Swap<T>(this List<T> list, int indexA, int indexB)
{
T tmp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = tmp;
return list;
}
Calling code
List<Customer> cusList = _uow.Customers.GetAll();
cusList.Swap(ddlItem1.SelectedValue, ddlItem2.SelectedValue);
_uow.Save();
When the above code is run, it swaps the item in the list but not the values for PriorityLevel.
If i was to swap the second item with the first item, the above code does it but in the following way (Note the ID of the record how they remain the same but order changes – in debug mode anyway)
Id Name Age PriorityLevel
2 Adam 40 2
1 Bill 50 1
but i want to have it so it does the below (Note the priority level)
Id Name Age PriorityLevel
1 Bill 50 2
2 Adam 40 1
How is this possible?
>Solution :
That’s general code for swapping list entries. You need something much more specific
public static void SwapPriorities(this List<Customer> list, int indexA, int indexB)
{
int tmp = list[indexA].Priority;
list[indexA].Priority = list[indexB].Priority;
list[indexB].Priority = tmp;
return list;
}
or simply
public static void SwapPriorities(Customer customerA, Customer customerB)
{
int tmp = CustomerA.Priority;
customerA.Priority = customerB.Priority;
customerB.Priority = tmp;
}