使用LINQ对对象进行区分

时间:2018-10-16 02:39:21

标签: c# linq linq-to-objects

我的数据如下图enter image description here

所以我使用anon对象将其加载到集合中,以绕过创建类

List<dynamic> myList = new List<dynamic>()
        {
            new {
                WorkOrderID = 40001,
                LastUpdatedAt = DateTime.Parse("2018-10-02"),
                Col3 = "abc",
                Col4 = "xyz"
            },
            new {
                WorkOrderID = 40001,
                LastUpdatedAt = DateTime.Parse("2017-06-01"),
                Col3 = "abc",
                Col4 = "xyz"
            },
            new {
                WorkOrderID = 40002,
                LastUpdatedAt = DateTime.Parse("2018-07-01"),
                Col3 = "abc",
                Col4 = "xyz"
            },
            new {
                WorkOrderID = 40003,
                LastUpdatedAt = DateTime.Parse("2018-09-01"),
                Col3 = "abc",
                Col4 = "xyz"
            },
            new {
                WorkOrderID = 40001,
                LastUpdatedAt = DateTime.Parse("2016-01-01"),
                Col3 = "abc",
                Col4 = "xyz"
            },
            new {
                WorkOrderID = 40002,
                LastUpdatedAt = DateTime.Parse("2016-12-01"),
                Col3 = "abc",
                Col4 = "xyz"
            },
        };

如何使用Linq-to-Objects仅提取最近更新的DISTINCT工作单。

换句话说,我应该以橙色突出显示3行。

  

var myFilteredList = myList.GroupBy(// ??完全丢失了...帮助...

3 个答案:

答案 0 :(得分:2)

如果我没有误会,您需要每个工作单的最新商品。

var latestWorkOrders = myList
    .GroupBy(w => w.WorkOrderID)
    .Select(g => g.OrderByDescending(w => w.LastUpdatedAt).First());

它将按WorkOrderID分组,并为每个分组选择最新的项目。

答案 1 :(得分:2)

以下代码使用GroupBy重载,因此可以在同一调用中完成元素选择,并将其转换为强类型的匿名对象。

var myFilteredList = myList
    .GroupBy(_ => (int)_.WorkOrderID, (k, g) =>
    {
        var recent = g.OrderByDescending(_ => _.LastUpdatedAt).First();
        return new
        {
            WorkOrderID = k,
            LastUpdatedAt = (DateTime)recent.LastUpdatedAt,
            Col3 = (string)recent.Col3,
            Col4 = (string)recent.Col4
        };
    });

Fiddle

答案 2 :(得分:0)

List<dynamic> list = myList
               .GroupBy(a => a.WorkOrderID )
               .OrderByDescending(b => b.LastUpdatedAt)
               .Select(g => g.FirstOrDefault())
               .ToList();

foreach (var p in list)
{
    Console.WriteLine(p.WorkOrderID + " : " + p.Col3);
}

就个人而言,动态并不是一个不错的选择。如果您有一个对象,则可以在该对象上实现EqualsGetHashCode。这样您可以:

var list = myList.Select(o => new { o.WorkOrderID, ... })
                                       .Distinct();

这要干净得多。