How to sort a list in ef core? or set a sort value ?

mc 3,681 Reputation points
2022-08-18T09:11:25.487+00:00

I am creating a table that can easy sort.

public MyClassA {  
public int Id{get;set;}  
public string Name{get;set;}  
public int Sort{get;set;}  
}  

If I use int Sort to sort the list It will be difficult to add a value between two items;

I can add it easy with sort to last one + 1 but move one to the item is not that easy.

1 2 3 4 5 6 7

I can add an 8
to
1 2 3 4 5 6 7 8

but I want to add one in the
1 2 3 4 5
here
6 7 8
I have to add 1 to the 6 7 8 to
1 2 3 4 5 6 7 8 9
right?
how to add one but I do not need add the other value

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 26,201 Reputation points
    2022-08-19T10:51:02.1+00:00

    If I understand, you want to add a new item to the list with a specific sort value. If the sort value exists in the list then increment each sort value in the list where the list sort value is greater than or equal to the new item's sort value.

        public static async Task Main(string[] passwordargs)  
        {  
            List<MyClassA> items = new List<MyClassA>()  
    ;       for(var i = 0; i<9; i++)  
            {  
                items.Add(new MyClassA()  
                {  
                    Id = i,  
                    Name = $"Name_{i}",  
                    Sort = i  
                });  
            }  
      
            MyClassA newItem = new MyClassA()  
            {  
                Id = 10,  
                Name = "NewName",  
                Sort = 7  
            };  
      
            List<MyClassA> results = InsertMyClassA(items, newItem);  
      
            foreach(var item in results)  
            {  
                Console.WriteLine($"{item.Id}\t{item.Name}\t{item.Sort}");  
            }  
      
        }  
      
        public static List<MyClassA> InsertMyClassA(List<MyClassA> list, MyClassA newItem)  
        {  
            foreach(var item in list)  
            {  
                if (item.Sort >= newItem.Sort)  
                {  
                    item.Sort += 1;  
                }  
            }  
      
            list.Add(newItem);  
            return list.OrderBy(i => i.Sort).ToList();  
        }