对集合进行多条件属性分组

实体类:

public class Person
    {
        public int ID { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 住址
        /// </summary>
        public string Addr { get; set; }
        /// <summary>
        /// 国家
        /// </summary>
        public string County { get; set; }
        /// <summary>
        /// 性别 F M
        /// </summary>
        public string  Sex { get; set; }
    }








实现:
class Program
    {
        static void Main(string[] args)
        {
            var lst = new List<Person> { 
             new Person{ ID=1,Name="AA", County="CN", Addr="JD1", Sex="F"},
             new Person{ ID=2,Name="BB", County="CN", Addr="JD1", Sex="M"},
             new Person{ ID=3,Name="CC", County="US", Addr="JD2", Sex="F"},
             new Person{ ID=4,Name="DD", County="US", Addr="JD2", Sex="M"},
             new Person{ ID=5,Name="EE", County="HK", Addr="JD3", Sex="F"},
             new Person{ ID=6,Name="FF", County="HK", Addr="JD4", Sex="M"},
             new Person{ ID=7,Name="GG", County="HK", Addr="JD5", Sex="F"},
            };
 
 
            var gps_1 = lst.GroupBy(x => (GetUnicIdetity(x.County)));//仅仅按照国家分组
            var gps_2 = lst.GroupBy(x => GetUnicIdetity(x.County, x.Sex));//按照国家+性别进行分组
 
            Console.WriteLine("单属性分组:");
            foreach (var g in gps_1)
            {
                Console.WriteLine(g.Key);
            }
            Console.WriteLine("下面是按照符合组键进行的分组:");
            foreach (var g in gps_2)
            {
                Console.WriteLine(g.Key);
            }
 
 
            Console.ReadKey();
        }
 
        private static string GetUnicIdetity(params object[] paras)
        {
            StringBuilder sb_result = new StringBuilder("");
            char spliterChar='-';
            if (null!=paras&&paras.Count()>0)
            {
                foreach (var item in paras)
                {
                    sb_result.Append(item).Append(spliterChar);
                }
                //移除掉最后一个-,也可以不移除
                if (sb_result.Length>1)
                {
                    sb_result.Remove(sb_result.Length - 1, 1);
                }
 
            }
            return sb_result.ToString();
        }
    }






posted @ 2014-12-26 17:50  特洛伊-Micro  阅读(573)  评论(0编辑  收藏  举报