class Range
{
public int Min { get; private set; }
public int Max { get; private set; }
public Range(int min_inclusive, int max_exclusive)
{
Min = min_inclusive;
Max = max_exclusive;
}
public bool Contains(decimal num)
{
return Min <= num && num < Max;
}
public override string ToString()
{
return string.Format("{0} ~ {1}", Min, Max);
}
}
static void Main(string[] args)
{
var ranges = new List<Range>()
{
new Range(0,10),
new Range(10,30),
new Range(30,35)
};
var numbers = new[] { 1.1m, 2, 36, -1m, 100.9m, 44, 19.0m };
//当range数目远大于numbers数目时用这个更高效
var accounting1 = ranges.ToDictionary(r => r, r => numbers.Count(n => r.Contains(n)));
//当numbers数目远大于range时用这个更高效
var accounting2 = numbers.Aggregate(ranges.ToDictionary(r => r, r => 0), (dict, n) =>
{
var range = dict.Keys.SingleOrDefault(r => r.Contains(n));
if (range != null) dict[range]++;
return dict;
});
}
\(≧▽≦)/ 敢不敢不这么强大