gpt4 book ai didi

c# - 如何从组中获取第一项并准备数据类对象

转载 作者:行者123 更新时间:2023-12-02 11:24:39 26 4
gpt4 key购买 nike

我有一个数据包列表,我正在其中根据 DateAndTime 进行排序和分组的ResultNamePacket 。并且仅选择 First项目。

 var packets = new List<Packet>
{
new Packet { Name = "P1", Result = new Result { Name = "N1", DateAndTime = new DateTime(2020, 05, 11, 10, 30, 50) }},
new Packet { Name = "P1", Result = new Result { Name = "N2", DateAndTime = new DateTime(2020, 05, 11, 10, 31, 50) }},
new Packet { Name = "P2", Result = new Result { Name = "N1", DateAndTime = new DateTime(2020, 05, 11, 10, 32, 50) }},
new Packet { Name = "P1", Result = new Result { Name = "N2", DateAndTime = new DateTime(2020, 05, 11, 10, 33, 50) }},
new Packet { Name = "P2", Result = new Result { Name = "N2", DateAndTime = new DateTime(2020, 05, 11, 10, 34, 50) }},
new Packet { Name = "P1", Result = new Result { Name = "N1", DateAndTime = new DateTime(2020, 05, 11, 10, 35, 50) }}
};

var resultData = packets.OrderByDescending(x => x.Result.DateAndTime).GroupBy(x => x.Name).Select(x => x.First());

支持类,

public class Packet
{
public string Name { get; set; }
public Result Result { get; set; }
}

public class Result
{
public string Name { get; set; }
public DateTime DateAndTime { get; set; }
}

现在我需要准备Data上面的物体 resultData ,

public class Data
{
public string PacketName { get; set; }
public DateTime PacketTime { get; set; }
}


var data=new Data
{
PacketName = resultData.???

}

如何做到这一点?另外OrderByDescending什么时候申请?

最佳答案

List<Data> datas = resultData.Select(x => new Data (){ PacketName = x.Name, PacketTime = x.Result.DateAndTime }).ToList(); 

或者

List<Data> datas = packets.OrderByDescending(x => x.Result.DateAndTime)
.GroupBy(x => x.Name)
.Select(x => new Data() { PacketName = x.First().Name, PacketTime = x.First().Result.DateAndTime })
.ToList();

关于c# - 如何从组中获取第一项并准备数据类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61723348/

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