.SelectMany与C# [英] .SelectMany with C#

查看:97
本文介绍了.SelectMany与C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这篇文章,我需要类似的东西

I found this post and I need something similar

stackoverflow.com/questions/41282053/groupby-multi-date-properties-by-month-and-year-in-linq/43112774#43112774

我需要按月和年分组,但同时我需要无法访问的主元素的属性

I need to group by month and year, but at the same time I need a property of the main element, which I can not access

var departments = stops 
    .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year }
    .Where(dt => dt != null).Select(dt => x.InitDate))
    .GroupBy(dt => new { dt.Month, dt.Year }) 
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year) 
    .Select(g => new 
    { 
        Key = g.Key.Month, 
        Año = g.Key.Year, 
        Duration = 0, 
        Count = g.Count() 
    });

我需要访问"stops.Duration",但是如果我这样做:.SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year, x.Duration }

I would need access to "stops.Duration" but if i do this: .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year, x.Duration }

它没有按月年分组我

有人可以帮助我吗?

对不起,我的英语,非常感谢

Sorry for my english and thank you very much

推荐答案

此代码应执行以下操作:

This code should do:

var departments = stops 
    .Where(stop => stop.InitDate != null)
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })
    .GroupBy(dt => new { dt.Month, dt.Year }) 
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year) 
    .Select(g => new 
    { 
        Key = g.Key.Month, 
        Año = g.Key.Year, 
        Duration = g.Sum(v => v.Duration), 
        Count = g.Count() 
    });

它选择持续时间,按月和年分组,并使用分组结果中的持续时间总和.

It selects the duration, groups on month and year, and uses the sum of the duration from the grouped result.

这篇关于.SelectMany与C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆