casillas
casillas

Reputation: 16813

Sort and Match List Item

I have the following List where each list item has Start and End values. Please observe that each list item's End value matches with next List item's Start value.

tableItems.Add (new SettingsCellItem() {Start=1000, End=4000});
tableItems.Add (new SettingsCellItem() {Start=4000, End=6000});
tableItems.Add (new SettingsCellItem() {Start=6000, End=8000});
tableItems.Add (new SettingsCellItem() {Start=8000, End=11300});
tableItems.Add (new SettingsCellItem() {Start=11300,End=12000});

User is allowed to update only Start Values and when user enter new Start values, List should be sorted based on Start value before it displays again.

Let's assume user updates the second list item from {Start=4000,End=6000} to {Start=140,End=6000}

List<SettingsCellItem> sortedList =tableItems.OrderBy(o=>o.Start).ToList();

I got the following output. As you observe End value does not match with Start value anymore.

Current Output:

{Start=140,  End=6000}
{Start=1000, End=4000}
{Start=6000, End=8000}
{Start=8000, End=11300}
{Start=11300,End=12000}

I wonder how could I able to get the following:

Desired Output

{Start=140,  End=1000}
{Start=1000, End=6000}
{Start=6000, End=8000}
{Start=8000, End=11300}
{Start=11300,End=12000}

Upvotes: 0

Views: 187

Answers (2)

Kevin
Kevin

Reputation: 561

The obvious answer that comes to mind would be to loop through the new list and update the end values to match the next item's start value. Something like this perhaps

public void UpdateEndValues(List<TypeLogSettingsCellItem> list)
 {
    int highestEndValue = list.Max (x => x.End);

    for(int i = 0; i < list.Count -1; i++)
    {
        list[i].End = list[i+1].Start;
    }

    list.Last.End = (list.Last.Start > highestEndValue) ? list.Last.Start : highestEndValue;
}

Note that the major difference between my code and the previous answer from pikciu is that mine preserves the final End value, which his/hers will not if the last CellItem is the one that was edited by the user

Updated: @texas pointed out that I was mishandling the case where the new start value is higher than the old highest end value, so I updated my code sample to cover that

Upvotes: 1

Tomasz Pikć
Tomasz Pikć

Reputation: 763

Update End after sorting by Start?

for(int i = 0; i < sortedList.Count - 1; i++)
{
    sortedList[i].End = sortedList[i+1].Start
}

Look at @Kevin Wells answer if you don't want to lose End value in case when you edit last element

Example for Select:

var normalizedList = sortedList.Select(
                              (e, i) => 
                                 new SettingsCellItem() 
                                 {
                                   Start = e.Start, 
                                   End = i < sortedList.Count - 1 
                                       ? sortedList[i+1].Start : e.End
                                 }).ToList()

Upvotes: 6

Related Questions