如何在数据列表中获取总月和日 [英] How to get total month and day in list of data
本文介绍了如何在数据列表中获取总月和日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好...
如何获得月份和月中总天数。
例如。
Hello...
How to get number of month and total day in month get.
for eg.
ArrayList array1 = new ArrayList();
array1.Add("9/22/20115");
array1.Add("9/23/20115");
array1.Add("9/24/20115");
array1.Add("9/25/20115");
array1.Add("9/26/20115");
array1.Add("9/27/20115");
array1.Add("9/28/20115");
array1.Add("9/29/20115");
array1.Add("9/30/20115");
array1.Add("10/1/20115");
Total Month :- 2(8,9)
Totay day :- 10 fix(8 month 9 day & 9 month 1 day)
就像c#中的输出一样。
just like this of output in c#.
推荐答案
一种非常有趣的方法是使用LINQ。请考虑以下代码:
One quite fun way is to use LINQ. Consider the following code:
System.Collections.ArrayList array1 = new System.Collections.ArrayList();
array1.Add("9/22/2015");
array1.Add("9/23/2015");
array1.Add("9/24/2015");
array1.Add("9/25/2015");
array1.Add("9/26/2015");
array1.Add("9/27/2015");
array1.Add("9/28/2015");
array1.Add("9/29/2015");
array1.Add("9/30/2015");
array1.Add("10/1/2015");
var months = from day in array1.OfType<string>()
select System.DateTime.Parse(day,
new System.Globalization.CultureInfo("en-US")).Month;
System.Diagnostics.Debug.WriteLine(string.Format("Months {0}",
months.Distinct().Count()));
var days = from day in array1.OfType<string>()
select System.DateTime.Parse(day,
new System.Globalization.CultureInfo("en-US")).Day;
System.Diagnostics.Debug.WriteLine(string.Format("Days {0}",
days.Distinct().Count()));
作为 Mika Wendelius [ ^ ]建议您必须使用Linq查询。我建议使用这样的东西:
As Mika Wendelius[^] suggested you have to use Linq query. I would suggest to use something like this:
var result = array1.Cast<string>()
.GroupBy(a=>Convert.ToDateTime(a).Month)
.Select(grp=>new
{
Month = grp.Key,
CountOfDaysInMonth = grp.Count()
});
这产生的结果如下:
This produces result as follow:
Month CountOfMonths
9 9
10 1
如需了解更多信息,请参阅:< a href =https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b> 101 LINQ样本 [ ^ ]
实现这一目标的另一种方法是使用查询如下:
For further information, please see: 101 LINQ Samples[^]
Another way to achieve that is to use query like this:
var result = array1.Cast<string>()
.GroupBy(a=>new{PeriodOfTime = Convert.ToDateTime(a).ToString("yyyy-MM")})
.Select(grp=>new
{
Period = grp.Key.PeriodOfTime,
TotalDaysInMonth = grp.Count()
});
结果:
Result:
Period TotalDaysInMonth
2015-09 9
2015-10 1
最后,你可以显示结果这样:
Finally, you can display the result this way:
Console.WriteLine("Total Months: {0}; Total Days: {1}", result.Count(), result.Sum(d=>d.TotalDaysInMonth));
//Total Months: 2; Total Days: 10
这篇关于如何在数据列表中获取总月和日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文