日期:2014-05-17  浏览次数:20641 次

请问,这种集合怎么处理
给定一个集合:
List<string> list_源 = new List<string>(){"1","3","4","2","1","3","1","2","1","1"};
按下面的条件分组:
List<string> list_A组 = new List<string>(){ "1","3"};
List<string> list_B组 = new List<string>(){ "2","4"};


要求把list_源中的元素分组,分组时,直到下一个元素不属于上一组,就新建,并加上改组的个数,组成一个字符串,要求最后返回一个分了组的List<string>
上面list_源的分组结果为:<A2,B2,A3,B1,A2>
解释,从开始,一个一个挨着来:
1、3属于A组,有2个,则为字符串A2
4、2属于B组,有两个,则为字符串B2
1、3、1属于A组,有3个,则为字符串A3
2属于B组,有1个,则为B1
1、1属于A组,则为A2


最后的字符串顺序必须正确。


请教计算过程,谢谢!!
------最佳解决方案--------------------
            List<string> list_源 = new List<string>() { "1", "3", "4", "2", "1", "3", "1", "2", "1", "1" };
            List<string> list_A组 = new List<string>() { "1", "3" };
            List<string> list_B组 = new List<string>() { "2", "4" };
            var str = string.Join("", list_源.Select(t => "[" + (list_A组.Contains(t) ? 1 : (list_B组.Contains(t) ? 2 : 0)) + ":" + t + "]").ToArray());
            var list = Regex.Matches(str, @"\[(\d+):(\w+)\](\[\1:(\w+)\])*").Cast<Match>().Select(t =>
                t.Groups[2].Value + string.Join("", t.Groups[4].Captures.Cast<Capture>().Select(tt => tt.Value).ToArray())
                ).ToArray();
------其他解决方案--------------------
用Dictionary和Linq可以搞定:
代码没有测试过,有问题自己修改

Dictionary<string, List<string>> dic = new <string, List<string>>();

dic.Add("A", list_A组);
dic.Add("B", list_B组);

int cur, total, count;
List<string> result = new List<string>();

cur = 0; total = list_源.Count;

while(cur < total)
{
   // 依次获取在各个分组中存在的连续项
   foreach(var key in dic.Keys)
   {
      var list = dic[key];
      var items = list_源.Skip(cur).TakeWhile(s => list.Contains(s));
      count = items.Count();
      // 有满足条件的记录下来
      if (count > 0)
     {
       cur += count;
       result.Add(key + count);
       if (cur == total) break;
      }
   }
}
// 输出结果
Console.WrintLine(string.Join(",", result.ToArray());

------其他解决方案--------------------