从实体列表中查找实体

时间:2012-10-23 15:40:25

标签: c# .net linq .net-4.0

我有一个如下所示的实体列表。

Entity1 { Id=1, From=01/01/2011, To=31/01/2011, Status=true }
Entity2 { Id=1, From=01/02/2011, To=28/02/2011, Status=false}
Entity2 { Id=2, From=01/02/2011, To=28/02/2011, Status=false}
Entity3 { Id=3, From=01/01/2011, To=31/01/2011, Status=true }
Entity4 { Id=4, From=01/01/2011, To=31/01/2011, Status=true }
Entity5 { Id=1, From=01/03/2011, To=31/03/2011, Status=false}
Entity6 { Id=4, From=31/03/2011, To=10/04/2011, Status=false}

我想找到具有最早日期和最新日期的实体。 (涵盖整个日期和日期的实体)

基本上我需要获得与日期不同的实体。此外,起始实体应具有最早的起始日期,最终实体应具有最新的截止日期

在这种情况下,预期结果是实体从 01/01/2011 开始到 10/04/2011

更新

Entity 1 has the oldest from date : 01/01/2011
Entiry 2 which falls under : 01/01/2011 and 10/04/2011
Entity 3 which falls under 01/01/2011 and 10/04/2011(but entity 1 has same from and to date as Entity3 so entity 3 not a valid)
Entity 4 which falls under 01/01/2011 and 10/04/2011(but entity 1 has same from and to date as Entity4 so entity 4 not a valid)
Entity 5 which falls under : 01/01/2011 and 10/04/2011
Entity 6 has the most recent To date : 10/04/2011
So Valid entries are Entity1, Entity2, Entity5, Entity6

我试过这样的事情

var dates = (EntityList.GroupBy(offer => offer.id)
             .Select(group =>
                 new { offerid = group.Key,
                       offers = group.OrderBy(o => o.From)
                       })
             .OrderBy(g => g.offers.First().From) 
        . FirstOrDefault
 ().offers.First();  

但我认为它应该没有分组,但我不太确定

感谢任何帮助

由于

2 个答案:

答案 0 :(得分:0)

var dates = from e in EntityList
            orderby e.Id
            group e by new { e.From, e.To } into g
            select g.First();

查询将仅返回具有相同from-to日期的组中的第一个(按id排序)实体。

答案 1 :(得分:0)

你不能使用这样的东西:

var selectedEntity = EntityList.OrderBy(e => e.From)
                               .ThenByDescending(e => e.To)
                               .FirstOrDefault();

更新:

你能使用Distinct方法吗?

var selectedEntity = EntityList.OrderBy(e => e.From)
                               .ThenByDescending(e => e.To)
                               .Distinct();