c# - 确定 List<T> 中的值跳跃

标签 c# .net linq

我有一个类:

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. 开始 = 1,结束 = 300
  2. 开始 = 301,结束 = 600
  3. 开始 = 601,结束 = 900
  4. 开始 = 1201,结束 = 1500
  5. 开始 = 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/

相关文章:

c# - 有没有办法获得 PostgreSQL 服务名称?

C# LINQ 和涉及大型数据集的计算

c# - Entity Framework 的多个条件以获得所需的记录

c# - 比较 C# 中 AM 和 PM 格式的时间值

.net - 使用 Nancy + TinyIoC 通过 Quartz JobFactory 注入(inject)依赖项

c# - linq 中不允许使用 String.Format 或 toString

c# - 在紫色屏幕中更改 RenderTarget 结果?

c# - 在数据库的 ListView 中将日期格式化为 dd/MM/yyyy

c# - 使用 Func<Inner,Outer,bool> 的 Linq GroupJoin?

.net - VB.Net 中被清除的对象列表(arrayLists)是什么?