我需要按C#
LINQ
这是我的代码:
public class Class1
{
public Nullable<DateTime> dt1 { get; set; }
public Nullable<DateTime> dt2 { get; set; }
}
Class1 obj1 = new Class1 { dt1 = new DateTime(2012, 11, 12),
dt2 = new DateTime(2012, 12, 12) };
Class1 obj2 = new Class1 { dt1 = new DateTime(2012, 11, 12),
dt2 = new DateTime(2012, 12, 12) };
Class1 obj3 = new Class1 { dt1 = null, dt2 = new DateTime(2012, 10, 12) };
Class1 obj4 = new Class1 { dt1 = new DateTime(2012, 10, 12), dt2 = null };
Class1 obj5 = new Class1 { dt1 = null, dt2 = new DateTime(2012, 11, 12) };
Class1 obj6 = new Class1 { dt1 = new DateTime(2013, 10, 12), dt2 = null };
List<Class1> listGoogleTimezone = new List<Class1>
{
obj1,
obj2,
obj3,
obj4,
obj5,
obj6
};
我要求的结果是这样的
MONTH YEAR COUNT
OCT 2012 2
NOV 2012 3
DEC 2012 2
帮帮我
答案 0 :(得分:4)
您需要使用SelectMany
收集所有日期(在此特定情况下过滤掉null
值),然后执行典型的GroupBy
/ Count
投影:< / p>
var result = listGoogleTimezone
.SelectMany(x => new[] { x.dt1, x.dt2 }.Where(dt => dt != null).Select(dt => dt.Value))
.GroupBy(dt => new { dt.Month, dt.Year })
.OrderBy(g => g.Key.Year).ThenBy(g => g.Key.Month) // optional
.Select(g => new
{
g.Key.Month,
g.Key.Year,
Count = g.Count()
}).ToList();
答案 1 :(得分:2)
如果您引用了MoreLinq
,则可以使用CountBy
使用make Ivan 的答案清除程序:
var result = listGoogleTimezone
.SelectMany(x => new[] { x.dt1, x.dt2 }
.Where(dt => dt != null)
.Select(dt => dt.Value))
.CountBy(x => new { Year = x.Year, Month = x.Month });
这将IEnumerable<KeyValuePair<TKey, int>>
TKey
Year
是一个匿名类型Month
和int
,而while len(d) > 0
是计数。