求数组中的数据并分组
原始数据如下:
class AType{
public DateTime time;
}
List<AType> lstA = new List<AType>()
{
new AType(){time = "2010-3-23 12:23:35"},
new AType(){time = "2010-3-23 23:23:35"},
new AType(){time = "2010-3-23 24:23:35"},
new AType(){time = "2010-3-24 1:23:35"},
new AType(){time = "2010-3-24 8:23:35"},
new AType(){time = "2010-3-24 9:23:35"},
new AType(){time = "2010-3-25 12:23:35"}
};
想求的结果如下:每天的最小和最大时间,如果一天只有一个时间,一个时间就OK
例如:
new AType(){time = "2010-3-23 12:23:35"},
new AType(){time = "2010-3-23 24:23:35"},
new AType(){time = "2010-3-24 1:23:35"},
new AType(){time = "2010-3-24 9:23:35"},
new AType(){time = "2010-3-25 12:23:35"}
------解决方案--------------------
不知道你是怎么做的,简单点的方法就是分开来做
List<AType> lstA = new List<AType>()
{
new AType(){time = new DateTime(2010, 3, 21, 3,10,10) },
new AType(){time = new DateTime(2010, 3, 21, 6,10,10)},
new AType(){time = new DateTime(2010, 3, 21, 8,10,10)},
new AType(){time = new DateTime(2010, 3, 22, 2,10,10)},
new AType(){time = new DateTime(2010, 3, 22, 4,10,10)},
new AType(){time = new DateTime(2010, 3, 24, 5,10,10)},
new AType(){time = new DateTime(2010, 3, 25, 6,10,10)}
};
var q1 = from a in lstA group a by a.time.Date into myGroup select new { dKey = myGroup.Key, tValue = myGroup };
List<AType> results = new List<AType>();
foreach (var member in q1)
{
if (member.tValue.Count() == 1)
{
results.Add(member.tValue.FirstOrDefault());
}
else
{
var minDate = (from d in member.tValue select d.time).Min();
var maxDate = (from d in member.tValue select d.time).Max();
results.Add( member.tValue.Where( t=>t.time == minDate ).FirstOrDefault() );
results.Add( member.tValue.Where( t=>t.time == maxDate ).FirstOrDefault() );
}
}
results.Dump();
}
class AType{
public DateTime time {get;set;}
自己去 linqpad 里 run 吧
------解决方案--------------------
using LINQ, too much eazy
DateTime[] dts = new DateTime[] {
new DateTime(2010,3,23,14,23,25),
new DateTime(2010,3,23,18,23,35),
new DateTime(2010,3,23,19,23,35),
new DateTime(2010,3,24,12,4,5),
new DateTime(2010,3,24,4,5,5),
new DateTime(2010,3,24,8,12,23),
new DateTime(2010,3,25,5,5,5)
};
var result = dts.GroupBy(s => s.Year.ToString() + s.Month.ToString()+s.Day.ToString()).SelectMany(s => (new DateTime[] { s.Min(), s.Max() }).Distinct()).ToArray();
Console.WriteLine(result);