Fork me on GitHub

Linq GroupBy

public class InterfaceKey : IComparable
    {
        /// <summary>
        /// 接口名称
        /// </summary>
        public string InterfaceName = string.Empty;
        /// <summary>
        /// 产品标识
        /// </summary>
        public string Aid = string.Empty;
        /// <summary>
        /// 版本标识
        /// </summary>
        public string Version = string.Empty;
        /// <summary>
        /// 平台标识
        /// </summary>
        public string OSID = string.Empty;
        /// <summary>
        /// 表示时间的字符串(具体到分钟。如:201206010001)
        /// </summary>
        public string FileName;

        public int CompareTo(object obj)
        {
            if (obj.GetType() != this.GetType())
            {
                return -1;
            }
            InterfaceKey selfObj = obj as InterfaceKey;
            int result = 0;
            if (this.InterfaceName == selfObj.InterfaceName && this.Aid == selfObj.Aid && this.Version == selfObj.Version && this.OSID == selfObj.OSID)
            {
                result = 1;
            }
            else
                result = -1;
            return result;
        }
        public override bool Equals(object obj)
        {
            if (obj.GetType() != this.GetType())
            {
                return false;
            }
            InterfaceKey other = obj as InterfaceKey;
            if (this.InterfaceName != other.InterfaceName || this.Version != other.Version || this.Aid != other.Aid || this.OSID != other.OSID)
            {
                return false;
            }
            return true;
        }

        public override int GetHashCode()
        {
            return this.InterfaceName.ToString().GetHashCode();
        }

    }
/// <summary>
    /// 封装接口需要统计的信息的数据结构(可扩展)
    /// </summary>
    public class InterfaceInfo
    {
        /// <summary>
        /// 接口调用次数
        /// </summary>
        public Int64 Frequency;

        /// <summary>
        /// 接口调用耗时
        /// </summary>
        public Int64 TimeConsuming;
    }
//Linq GroupBy hourMergerInfo:Dictionary<InterfaceKey, InterfaceInfo>
var query = hourMergerInfo.GroupBy(v => v.Key.InterfaceName).ToDictionary(x => x.Key,
                x => new
                {
                    SumFrequency = x.Sum(y => y.Value.Frequency),
                    AvgTimeConsuming = x.Average(y => y.Value.TimeConsuming * 1.0 / y.Value.Frequency)
                });

 foreach (var item in query)
                {
                    string key = item.Key;
                    Int64 sumFrequency = item.Value.SumFrequency;
                    double avgTimeConsuming = item.Value.AvgTimeConsuming;
                }
posted @ 2012-12-06 12:02  zhanjindong  阅读(1680)  评论(0编辑  收藏  举报
TOP