question

StefanoM-9408 avatar image
0 Votes"
StefanoM-9408 asked ColeXia-MSFT answered

Insert elements at the bottom of an ObservableCollection and not at the beginning

I have a CollectionView with some groups. The groups to be inserted are read from a SqLite database, sorted in chronological order and inserted into the CollectionView. Each group has elements, also in chronological order. I have a button that allows me to insert new elements, always within groups, if it already exists, otherwise it creates a new one. when he has to insert new groups, I would like them to be added starting from the last element already present in the CollectionView, then from the bottom, while now they are added to me at the top

Here is the code for both when I insert elements at the start of the page and when I insert elements afterwards

 foreach (MyElement hd in MydataBase.Reerse())
 {
        MyGroup group = new MyGroup("Name Group", new ObservableCollection<MyElement>());
    
         if (!MyCollection.Contains(group))
         {
               MyCollection.Add(group);
         }
        group.Add(hd);
 }

CollectionView.ItemsSource = MyCollection.Reverse();

But when I add them later:

 MyGroup hgroup = new MyGroup("NameGroup", new ObservableCollection<Myelement>());
    
   hgroup.Add(MyElement)
   MyCollection.Add(hgroup);
 CollectionView.ItemsSource = MyCollection.Reverse();

I use the Reverse() method because otherwise when the page starts it displays the elements in reverse order
.

Obviously he has to insert the elements at the beginning if in the Datetime property they have inside them they have a lower date than the other elements that already exist, but the logic inside the app is already there. The problem arises for elements that are antecedent (in the DateTime property) compared to those already in the collection

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ColeXia-MSFT avatar image
0 Votes"
ColeXia-MSFT answered

Hello,

Welcome to Microsoft Q&A!

If I understand correctly , you can insert the item with index .

Replace

MyCollection.Add(hgroup);

With

MyCollection.Insert(0 ,hgroup);


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.