0

Below is my query- when a new element comes to the StoriesCollection RangeObservableCollection.
I'm moving the elements in the collection based on below logic:
(pinned entries should be fixed in the grid so I am checking if the new entry is pinned/unpinned, if it is unpinned then I am moving the other elements in the collection by one place each to fit the new element).
please help to optimize it with LINQ.

private void AdjustPinnedStories()
    {
        for (int i = 1; i < StoriesCollection.Count; i++)
        {
            if (StoriesCollection[i].IsPinned)
            {
                if (!StoriesCollection[i - 1].IsPinned)
                {
                    StoriesCollection.Move(i, i - 1);
                }
            }
        }
    }
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
Rahul Sharma
  • 35
  • 2
  • 8
  • 1
    LINQ is about convenience and not about efficiency. Its like asking to help win an F1 race with a luxury motor home. – Mat J Jul 19 '20 at 11:29
  • 1
    Also, LINQ is for querying, and generally shouldn't be used for mutational purposes (i.e. your `Move` method), although you could hack a solution using `Select`. – Johnathan Barclay Jul 19 '20 at 11:32

1 Answers1

0

LINQ is not going to make your code more optimized, at least not in the sense of faster. It introduces some overhead and still has to go through the for loop, so in facts it’s going to be (marginally) slower.

The advantage of LINQ is faster And shorter code writing. If your loop already does what you want, you are better with leaving it as is.

Check this question for more details.

kefren
  • 1,042
  • 7
  • 12