日期:2014-05-17 浏览次数:21172 次
{ {"1","aaa"}, {"1","bbb"}, {"2","ccc"}, {"2","ddd"}, {"3","uuu"}, {"1","eee"}, {"4","aaa"}, {"4","qqq"} }
string[,] values = { { "1", "aaa" }, { "1", "bbb" }, { "2", "ccc" }, { "2", "ddd" }, { "3", "uuu" }, { "1", "eee" }, { "4", "aaa" }, { "4", "qqq" } }; SortedList<string, string> sortedList = new SortedList<string, string>(); for (int i = 0; i < values.GetLength(0); i++) { if (sortedList.ContainsKey(values[i, 0])) sortedList[values[i, 0]] += "," + values[i, 1]; else sortedList.Add(values[i, 0], values[i, 1]); } for (int i = 0; i < sortedList.Count; i++) if (!sortedList[sortedList.Keys[i]].Contains(',')) sortedList.RemoveAt(i--); if (sortedList.Count > 1) { for (int i = 0; i < sortedList.Count; i++) { for (int j = i + 1; j < sortedList.Count; j++) { string[] values1 = sortedList[sortedList.Keys[i]].Split(','); string[] values2 = sortedList[sortedList.Keys[j]].Split(','); if (values1.Intersect(values2).Count() > 0) { sortedList[sortedList.Keys[i]] = string.Join(",", values1.Union(values2).ToArray()); sortedList.RemoveAt(j--); } } } } foreach (KeyValuePair<string, string> pair in sortedList) Console.WriteLine(pair.Value);
------解决方案--------------------
namespace SumString { class Program { static string[,] str = new string[,] { { "1", "aaa" }, { "1", "bbb" }, { "2", "ccc" }, { "2", "ddd" }, { "3", "uuu" }, { "1", "eee" }, { "4", "aaa" }, { "4", "qqq" } }; static List<string[,]> list = new List<string[,]>(); static List<string> listid = new List<string>(); static void Main(string[] args) { Addlist(); foreach (string[,] str in list) { if (!listid.Contains(str[0, 0])) { if(SumString(str).TrimEnd(new char[]{','}).Contains(",")) Console.WriteLine("{0}--{1}", str[0, 0], SumString(str).TrimEnd(new char[]{','})); } listid.Add(str[0,0]); } Console.ReadKey(); } public static string SumString(string [,] para) { string str=""; foreach (string[,] s in list) { if (s[0, 0] == para[0,0]) { str += s[0, 1] + ","; } } return str; } public static void Addlist( )