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

标签 c#

我有一个数据包列表,我正在其中根据 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/

相关文章:

c# - LINQ - 以列名作为字符串参数访问列

c# - 在模型更改时更新数据库架构而不会丢失数据

c# - 调用其他代码是否违反(SOLID)单一责任原则(SRP)?

c# - 将字节数组与掩码进行比较

c# - 我如何在类型安全的枚举模式上使用 switch 语句

c# - 自定义消息框

c# - 在 C# 中跨继承边界重载?

c# - lambda 表达式中的空值 - Entity Framework

c# - 如何简化与 Entity Framework 的多对多关系的访问?

c# - 托管 CLR 与使用 ClrCreateManagedInstance - 有什么好处?