1using System; 2using System.Collections.Generic; 3using System.Diagnostics; 4using System.Linq; 5using System.Text; 6using System.Threading.Tasks; 7 8namespace listTst 9{ 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 var sw = Stopwatch.StartNew(); 15 var array = new List<Storage>() 16 { 17 new Storage{ Id = 1, Name = "A" }, 18 new Storage{ Id = 2, Name = "B" }, 19 new Storage{ Id = 3, Name = "C" }, 20 new Storage{ Id = 4, Name = "D" }, 21 new Storage{ Id = 5, Name = "E" }, 22 new Storage{ Id = 6, Name = "F" }, 23 new Storage{ Id = 7, Name = "G" }, 24 new Storage{ Id = 8, Name = "H" }, 25 new Storage{ Id = 9, Name = "I" }, 26 }; 27 28 var result = new List<Group>(); 29 array.ForEach(a => { result.Add(new Group(a)); }); 30 for (int count = 2; count <= array.Count; count++) 31 { 32 Test(result, array, 0, count); 33 } 34 sw.Stop(); 35 36 foreach (var group in result) 37 { 38 Console.WriteLine(group.Name); 39 } 40 Console.WriteLine($"组合数量:{result.Count}"); 41 Console.WriteLine($"耗时:{sw.ElapsedMilliseconds}ms"); 42 Console.ReadLine(); 43 } 44 45 static void Test(List<Group> result, List<Storage> array, int begin, int count) 46 { 47 var list = new List<Storage>(); 48 var end = begin + count - 1; 49 if (end > array.Count) return; 50 for (int i = begin; i < end; i++) 51 { 52 list.Add(array[i]); 53 } 54 if (list.Count < count) 55 { 56 for (int index = end; index < array.Count; index++) 57 { 58 var group = new Group(list); 59 group.Storages.Add(array[index]); 60 result.Add(group); 61 } 62 } 63 64 if (++begin < array.Count) Test(result, array, begin, count); 65 } 66 67 class Group 68 { 69 public Group(Storage storage) 70 { 71 Storages.Add(storage); 72 } 73 public Group(List<Storage> list) 74 { 75 Storages.AddRange(list); 76 } 77 public string Name => string.Concat(Storages.Select(a => a.Name)); 78 public List<Storage> Storages = new List<Storage>(); 79 } 80 81 class Storage 82 { 83 public int Id { get; set; } 84 public string Name { get; set; } 85 } 86 } 87}



