码迷,mamicode.com
首页 > Windows程序 > 详细

C# 使用Dictionary、linq实现根据集合里面的字符串进行分组

时间:2014-11-29 00:07:09      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   使用   sp   for   

分组两种方法:

List<string> list = new List<string>() { "1_32", "2_10", "1_8", "1_25", "2_3", "3_5", "5_15", "3_16" };
            
            //对上面集合里面的字符串按照“_”进行分组。

            #region //使用字典,键值对集合保存分组数据。
            Dictionary<string, List<string>> groupDic = new Dictionary<string, List<string>>();
            foreach (var item in list)
            {
                //取KEY值
                string key = item.Split(_)[0];
                //根据key值判断集合中是否存在指定的键,不存在则创建一个。
                if (!groupDic.ContainsKey(key))
                {
                    groupDic.Add(key, new List<string>()); //初始化
                }
                groupDic[key].Add(item); //直接把当前元素添加到,key对应的List集合中。
            }

            foreach (var item in groupDic)
            {
                var s = groupDic[item.Key];
                for (int i = 0; i < s.Count; i++)
                {
                    Console.WriteLine("KEY:{0} Value:{1}", item.Key, s[i]);
                }
            } 
            #endregion
            Console.WriteLine();

            #region //使用linq 分组
            var groupList = from s in list
                            group s by s.Split(_)[0] into g
                            select g;

            foreach (var item in groupList)
            {
                var s = groupDic[item.Key];
                for (int i = 0; i < s.Count; i++)
                {
                    Console.WriteLine("KEY:{0} Value:{1}", item.Key, s[i]);
                }
            } 
            #endregion

bubuko.com,布布扣

C# 使用Dictionary、linq实现根据集合里面的字符串进行分组

标签:style   blog   http   io   ar   color   使用   sp   for   

原文地址:http://www.cnblogs.com/han1982/p/4129528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!