C# 一个数组集合,任意组合,并且不重复

Posted chxl800

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 一个数组集合,任意组合,并且不重复相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace listTst

    class Program
    
        static void Main(string[] args)
        
            var sw = Stopwatch.StartNew();
            var array = new List<Storage>()
            
                new Storage Id = 1, Name = "A" ,
                new Storage Id = 2, Name = "B" ,
                new Storage Id = 3, Name = "C" ,
                new Storage Id = 4, Name = "D" ,
                new Storage Id = 5, Name = "E" ,
                new Storage Id = 6, Name = "F" ,
                new Storage Id = 7, Name = "G" ,
                new Storage Id = 8, Name = "H" ,
                new Storage Id = 9, Name = "I" ,
            ;

            var result = new List<Group>();
            array.ForEach(a =>  result.Add(new Group(a)); );
            for (int count = 2; count <= array.Count; count++)
            
                Test(result, array, 0, count);
            
            sw.Stop();

            foreach (var group in result)
            
                Console.WriteLine(group.Name);
            
            Console.WriteLine($"组合数量:result.Count");
            Console.WriteLine($"耗时:sw.ElapsedMillisecondsms");
            Console.ReadLine();
        

        static void Test(List<Group> result, List<Storage> array, int begin, int count)
        
            var list = new List<Storage>();
            var end = begin + count - 1;
            if (end > array.Count) return;
            for (int i = begin; i < end; i++)
            
                list.Add(array[i]);
            
            if (list.Count < count)
            
                for (int index = end; index < array.Count; index++)
                
                    var group = new Group(list);
                    group.Storages.Add(array[index]);
                    result.Add(group);
                
            

            if (++begin < array.Count) Test(result, array, begin, count);
        

        class Group
        
            public Group(Storage storage)
            
                Storages.Add(storage);
            
            public Group(List<Storage> list)
            
                Storages.AddRange(list);
            
            public string Name => string.Concat(Storages.Select(a => a.Name));
            public List<Storage> Storages = new List<Storage>();
        

        class Storage
        
            public int Id  get; set; 
            public string Name  get; set; 
        
    

 

技术图片

技术图片

技术图片

技术图片

以上是关于C# 一个数组集合,任意组合,并且不重复的主要内容,如果未能解决你的问题,请参考以下文章

2d 数组随机数(10 行,6 列)不重复到文件 C#

面试题03. 数组中重复的数字

哈希集合

哈希集合

用java找出这几个list,所有可能的组合,并且组合结果的list中的数据不允许重复

C#:组合相同列表的两个元素(不重复)