我有一个类:
public class ShipmentInformation
{
public string OuterNo { get; set; }
public long Start { get; set; }
public long End { get; set; }
}
我有一个 List<ShipmentInformation>
名为 Results
的变量.
然后我做:
List<ShipmentInformation> FinalResults = new List<ShipmentInformation>();
var OuterNumbers = Results.GroupBy(x => x.OuterNo);
foreach(var item in OuterNumbers)
{
var orderedData = item.OrderBy(x => x.Start);
ShipmentInformation shipment = new ShipmentInformation();
shipment.OuterNo = item.Key;
shipment.Start = orderedData.First().Start;
shipment.End = orderedData.Last().End;
FinalResults.Add(shipment);
}
我现在遇到的问题是,在每个分组项目中,我都有各种 ShipmentInformation,但起始编号可能不是按 x 顺序排列的。 x 可以是 300 或 200,具体取决于传入参数。为了说明我可以
- 开始 = 1,结束 = 300
- 开始 = 301,结束 = 600
- 开始 = 601,结束 = 900
- 开始 = 1201,结束 = 1500
- 开始 = 1501,结束 = 1800
因为我有这个跳转,所以我不能使用上面的循环来创建 ShipmentInformation
的实例并取出 orderedData
中的第一项和最后一项使用他们的数据来填充该实例。
我想要一些方法来识别 300 或 200 的跳跃,并创建一个 ShipmentInformation 实例以添加到 FinalResults,其中数据是连续的。
使用上面的示例,我将有 2 个 ShipmentInformation 实例,开始时间为 1,结束时间为 900,另一个开始时间为 1201,结束时间为 1800
最佳答案
尝试以下操作:
private static IEnumerable<ShipmentInformation> Compress(IEnumerable<ShipmentInformation> shipments)
{
var orderedData = shipments.OrderBy(s => s.OuterNo).ThenBy(s => s.Start);
using (var enumerator = orderedData.GetEnumerator())
{
ShipmentInformation compressed = null;
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (compressed == null)
{
compressed = current;
continue;
}
if (compressed.OuterNo != current.OuterNo || compressed.End < current.Start - 1)
{
yield return compressed;
compressed = current;
continue;
}
compressed.End = current.End;
}
if (compressed != null)
{
yield return compressed;
}
}
}
像这样使用:
var finalResults = Results.SelectMany(Compress).ToList();
关于c# - 确定 List<T> 中的值跳跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931425/