简体   繁体   中英

Inserting into a C# List of Objects that uses a Property of the Object to Sort

There's a list of objects, each object representing a record from a database. To sort the records there is a property called SortOrder. Here's a sample object:

public class GroupInfo
{
    public int Id { get; set; }
    public string Text { get; set; }
    public int SortOrder { get; set; }

        public GroupInfo()
        {
            Id = 0;
            Text = string.Empty;
            SortOrder = 1;
        }
}

A list object would look like this:

var list = new List<GroupInfo>();

I need to be able to change the SortOrder and update the SortOrder on the other objects in the list. I figured out how to sort up or down by one. I need to know how to change it by more than one and adjust the SortOrder on the other records. Any ideas?

This could be done by first getting the original SortOrder and the updated SortOrder . You would then iterate through your collection and adjust the SortOrder of any other GroupInfo objects that fall inside the range between original and updated . you could put all of this in a "SetSortOrder" function that takes in the containing collection.

public static void SetSortOrder(List<GroupInfo> groupInfos, GroupInfo target, int newSortOrder)
{
    if (newSortOrder == target.SortOrder)
    {
        return; // No change
    }
    // If newSortOrder > SortOrder, shift all GroupInfos in that range down
    // Otherwise, shift them up
    int sortOrderAdjustment = (newSortOrder > target.SortOrder ? -1 : 1);
    // Get the range of SortOrders that must be updated
    int bottom = Math.Min(newSortOrder, target.SortOrder);
    int top = Math.Max(newSortOrder, target.SortOrder);
    // Get the GroupInfos that fall within our range
    var groupInfosToUpdate = from g in groupInfos
                                where g.Id != target.Id
                                && g.SortOrder >= bottom
                                && g.SortOrder <= top
                                select g;
    // Do the updates
    foreach (GroupInfo g in groupInfosToUpdate)
    {
        g.SortOrder += sortOrderAdjustment;
    }

    target.SortOrder = newSortOrder;
    // Uncomment this if you want the list to resort every time you update
    // one of its members (not a good idea if you're doing bulk changes)
    //groupInfos.Sort((info1, info2) => info1.SortOrder.CompareTo(info2.SortOrder));
}

Update: As suggested, I moved the logic into a static helper function.

var sortedList = list.OrderBy(item => item.SortOrder);

Edit: Sorry, I misunderstood. You will need to write yourself a method outside of GroupInfo to handle the updating of that property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM