ganilyalcin ganilyalcin - 2 months ago 10
C# Question

How to check if a list is sorted consecutively?

I need to re-order a list consecutively if it is already not. Can anyone suggest a way to check it so that I can write an extension method to call like this?

var cglist = collectionGroups.OrderBy(x => x.Sequence).ToList();

if (cglist.IsConsecutive)
for (int i = 0; i < cglist.Count(); i++)
//sorting logic...

is not an incremented property in the entity and has duplicates and missing values. This data is fed to my context from an outer source which I have no control of. So I need to use it in a reordering method and make it adjacent

I could find the closest solution from this answer here which does not really seem to be checking adjacency.


The only way to check if the list is sorted is to go through every item in the list and compare it to the next item, in which case you might as well just call sort in the first place as that will perform the exact same check and sort anything out of order

Edit: i'm suspicious of the fact that you keep using the word "consecutively"

if you are looking for Missing or Duplicated Values then that is not mentioned in your question at all, but if that is the case a simple left join will do that for you with no need of sorting

var min = collectionGroups.Min(x => x.Sequence);
var deviation = collectionGroups.Max(x => x.Sequence) - min;

var result = from i in Enumerable.Range(min, deviation )
             join c in collectionGroups on i equals c.Sequence into grp;
             from g in grp.DefaultIfEmpty()
             where g.Count() != 1
             select new{ ID=g.Key, Count=g.Count()};

this will then return a list of duplicate or missing values no sorting needed

Edit in reply to comment by juunas

var data = Enumerable.Range(0, 20000000).ToList();
bool sort = false;
for (int i = 0; i < data.Count - 1; i++)
    if (data[i] > data[i + 1])
        sort = true;
if (sort) data.Sort();

884 ms

Compared to

var data = Enumerable.Range(0, 20000000).ToList();