开满天机
尝试这个:public static IEnumerable<IList<Couple>> Split(IEnumerable<Couple> couples){ using (var enumerator = couples.GetEnumerator()) { if (!enumerator.MoveNext()) { yield break; } var current = enumerator.Current; var group = new List<Couple> { current }; while (enumerator.MoveNext()) { var next = enumerator.Current; if (current.Indicator.Equals(next.Indicator)) { group.Add(next); } else { yield return group; group = new List<Couple> { next }; } current = next; } yield return group; }}例子:var couples = new List<Couple> { new Couple("a",false), new Couple("b",false), new Couple("c",true), new Couple("d",false), new Couple("e",false), new Couple("f",true), new Couple("g",true), new Couple("h",true), new Couple("i",false), new Couple("j",true), new Couple("k",true), new Couple("l",false), new Couple("m",false),};var groupNr = 1;foreach (var couplesGroup in Split(couples)){ Console.WriteLine($"List {groupNr++}: "); foreach (var couple in couplesGroup) { Console.WriteLine($"{couple.Text, 10}, {couple.Indicator}"); } Console.WriteLine();}
慕尼黑的夜晚无繁华
这是一个不使用 Linq 的解决方案:class Program{ public class Couple { public string Text; public bool Indicator; public Couple(string text, bool indicator) { Text = text; Indicator = indicator; } } static void Main(string[] args) { var list = new List<Couple>(); list.Add(new Couple("a", false)); list.Add(new Couple("b", false)); list.Add(new Couple("c", true)); list.Add(new Couple("d", false)); list.Add(new Couple("e", false)); list.Add(new Couple("f", true)); list.Add(new Couple("g", true)); list.Add(new Couple("h", true)); list.Add(new Couple("i", false)); list.Add(new Couple("j", true)); list.Add(new Couple("k", true)); list.Add(new Couple("l", false)); list.Add(new Couple("m", false)); var result = new List<List<Couple>>(); int index = 0; bool last = list[0].Indicator; result.Add(new List<Couple>()); foreach ( var item in list ) { if ( item.Indicator != last ) { index++; result.Add(new List<Couple>()); } last = item.Indicator; result[index].Add(item); } for ( index = 0; index < result.Count; index++ ) { Console.WriteLine($"List n°{index}"); foreach ( var item in result[index] ) Console.WriteLine($" text: {item.Text}"); } Console.WriteLine(""); Console.ReadKey(); }