首页 / C# / c# – 确定List中的值跳转
c# – 确定List中的值跳转
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 确定List中的值跳转,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1896字,纯文字阅读大概需要3分钟。
内容图文
我有一节课:
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
> Start = 1201,End = 1500
>开始= 1501,结束= 1800
因为我有这个跳转,所以我不能使用上面的循环来创建ShipmentInformation的实例,并使用orderedData中的第一个和最后一个项来使用它们的数据来填充该实例.
我想要一些方法来识别300或200的跳转,并创建一个ShipmentInformation实例,以添加到FinalResults,其中数据是sequnetial.
使用上面的例子,我将有2个ShipmentInformation实例,其中Start为1,End为900,另一个实例为Start of 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中的值跳转全部内容,希望文章能够帮你解决c# – 确定List中的值跳转所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。