c# - 在 C# 中检查序列的正确顺序

标签 c# algorithm

我正在寻找一种方法来“检测”有序对象序列是否乱序。

我试着用一个简单的例子来解释它:

我正在使用 TourStop 的 IEnumerable,其定义如下:

class TourStop 
{
    public int Id {get;set;}
    public int Sorting {get;set;}
    public string LocationTitle {get;set;}
    public bool Done {get;set;}
}

由于我的软件是供人类使用的,因此用户可能会以随机顺序设置 done 属性,这会导致“处理顺序”出现间隙。这就是我想从集合中提取的内容:“给我所有未完成且似乎出现故障的 TourStops”。

现在是棘手的部分!以下是一些作为简单 bool 数组的示例:

[1,1,1,0,0,0] // the algorithm should return nothing. The first three elements are processed in correct order and the rest of them may not be processed yet
[0,1,1,0,0,0] // here the algorithm should return only the first element
[1,0,0,1,1,0] // here the algorithm should return only the 2nd and 3rd element

对如何构建这样的查询有任何想法吗?

最佳答案

假设您有 ListTourStop。因此,您需要找到最后一个 "1" 之前的所有 "0":

List<TourStop> tourStops = new List<TourStop>();

// initialize list with your values

int index = tourStops.FindLastIndex((t) => t.Done);

List<TourStop> outOfOrder = null;

if (index > 0)
{
    outOfOrder = tourStops.Where((el) => !el.Done && tourStops.LastIndexOf(el) < index).ToList();
}

之后您可以检查是否 outOfOrder == null

如果是这样,则没有乱序元素。

如果不是,outOfOrder 将包含所有乱序元素。

此外,您可以尝试查询 @juharr 评论过的内容。

关于c# - 在 C# 中检查序列的正确顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41593036/

相关文章:

c# - 如何在 C# 中获取安装程序类中的 msi 路径

c# - 找不到文件异常 - Windows Phone

c# - 在 C Sharp 中模拟值类型多态性

algorithm - 最小化数组中相关项之间的距离

ios - 循环数组并使其为空。为什么它表现得很奇怪?

algorithm - 将加权图划分为同等权重的组

c# - 如何从安装程序获取路径以及如何在我的应用程序中设置?

algorithm - 在 n+2k-3 次比较中找到大小为 (2^k +1) 的数组中的第三大元素

algorithm - 什么是阶符号 f(n)=O(g(n))?

c# - 在绑定(bind)源中循环