按日期分组。日期

时间:2018-03-12 06:48:38

标签: c# .net linq

我正在努力做一个小组。我有以下列表:

 Date = 10/03 06:40 AM, Val = 10  
 Date = 10/03 08:55 PM, Val = 5  
 Date = 11/03 06:40 AM, Val = 5  
 Date = 11/03 10:50 AM, Val = 9  
 Date = 11/03 06:40 PM, Val = 14  

我想要这个清单:

 Date = 10/03, Val = 5  
 Date = 11/03, Val = 14

因此,列表按Date.Date分组,但Val取决于Max(d => d.Date)

我是用foreach做到的,但我很确定我们可以使用LINQ(groupbyselect)做些更好的事情。有任何想法吗?

干杯

4 个答案:

答案 0 :(得分:2)

我相信你想要像

这样的东西
static T MaxBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector)
where TKey: IComparable<TKey> =>
    source.OrderByDescending(selector).First();

然后

from item in items
group item by item.Date.Date into byDate
select new
{
    Date = byDate.Key,
    byDate.MaxBy(item => item.Date).Val
} 

如果您不想创建专用方法,您当然也可以内联

from item in items
group item by item.Date.Date into byDate
let ordered = from item in byDate
              orderby item.Date descending
              select item.Val
select new
{
    Date = byDate.Key,
    Val = ordered.First() 
}

注意:感谢mjwills指出了我能够纠正的错误

答案 1 :(得分:1)

它应该是这样的:

export ANDROID_HOME={YOUR_PATH}

export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

source ~/.bash_profile

答案 2 :(得分:0)

以下内容:

values
    .GroupBy(value => value.Date.Date)
    .Select(grouped => new
        {
            Date = grouped.Key,
            Val = values.First(value => value.Date == grouped.Date.Max()).Val
        });

答案 3 :(得分:-1)

以下是我最终的结果:

示例实体:

public class ExampleEntity
{
    public DateTime Date { get; set; }

    public int Val { get; set; }
}

示例代码:

var listOfExampleEntity = new List<ExampleEntity>()
        {
            new ExampleEntity()
            {
                Date = new DateTime(2018, 10, 03, 3, 40, 00),
                Val =2
            },
            new ExampleEntity()
            {
                Date = new DateTime(2018, 10, 03, 4, 40, 00),
                Val =2
            },new ExampleEntity()
            {
                Date = new DateTime(2018, 11, 03, 5, 40, 00),
                Val =5
            },new ExampleEntity()
            {
                Date = new DateTime(2018, 10, 03, 3, 40, 00),
                Val =2
            },new ExampleEntity()
            {
                Date = new DateTime(2018, 11, 03, 7, 40, 00),
                Val =3
            },new ExampleEntity()
            {
                Date = new DateTime(2018, 11, 03, 8, 40, 00),
                Val =4
            },
        };

        var temp = listOfExampleEntity.GroupBy(
                    p => p.Date.Date,
                    p => p.Val,
                    (date, val) => new { Date = date, Value = val.Last() });