简体   繁体   English

如何检查列表是否连续排序?

[英]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...
    } 
 }

x.Sequence is not an incremented property in the entity and has duplicates and missing values. x.Sequence不是实体中的增量属性,并且具有重复项和缺失值。 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 检查列表是否已排序的唯一方法是遍历列表中的每个项目,然后将其与下一个项目进行比较,在这种情况下,您最好只调用sort,因为它将执行完全相同的检查并乱序排序

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 编辑以回复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;
        break;
    }
}
if (sort) data.Sort();

884 ms 884毫秒

Compared to 相比

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

651ms 651ms

You can use the solution included in this answer . 您可以使用此答案中包含的解决方案。 You'd only need to change the checks >=0 and <=0 to ==1 and ==-1 . 您只需要将>=0<=0的检查更改为==1==-1

Use following loop to check sorting 使用以下循环检查排序

bool isSorted = true;

for(int i = 0;i < cglist.Count; i++)
{
   if( i == cglist.Count - 1)
   {
      break;
   }

   if(cglist[i] > cglist[i + 1])
   {
      isSorted = false;
   }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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