gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:15:33 25 4
gpt4 key购买 nike

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

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

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com