//對下面集合里面的字符串按照“_”進行分組。 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
使用linq
#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
使用lambda:
#region //使用lambda 分組 var groupList2 = list.GroupBy(s => s.Split('_')[0]).Select(g => g); foreach (var item in groupList2) { var s = groupDic[item.Key]; for (int i = 0; i < s.Count; i++) { Console.WriteLine("KEY:{0} Value:{1}", item.Key, s[i]); } } #endregion