2016-07-29 51 views
0

我需要任何字符串列表输出所有可能性。像那样。 这是让我720不同的字符串。我怎样才能得到输出字符串数组所有的可能性与组合?

List<String> items = new List<String>(); 
     items.AddRange(new String[] { "a", "b", "c", "d", "e", "f" }); 

输出;

1-)ABCDEF

2-)abcdfe

3-)ABCEDF

4-)abcefd

5-)abcfde

6-)abcfed

7-)abdcef

8-)abdcfe

9-)abdecf

10-)abdefc

11-)...........

12-).. .........

13-)bacdef

720 - )..........

+1

所以你有什么尝试? –

+0

bsouiler谢谢我现在尝试。 –

+0

你怎么知道它给你'720'不同的字符串? –

回答

2

在这里你去:

using System; 
using System.Collections.Generic; 
using System.Linq; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main() 
     { 
      List<String> items = new List<String>(); 
      items.AddRange(new String[] { "a", "b", "c", "d", "e", "f" }); 

      int i = 0; 

      foreach (var permutation in Permute(items)) 
       Console.WriteLine(++i + ": " + string.Join(" ", permutation)); 
     } 

     public static IEnumerable<IEnumerable<T>> Permute<T>(IEnumerable<T> seq) 
     { 
      return 
       from item in seq.Select((value, index) => new {value, index}) 
       from remainder in seq.Count() == 1 ? new[]{new T[0]} : Permute(allExcept(seq, item.index)) 
       select new[]{item.value}.Concat(remainder); 
     } 

     static IEnumerable<T> allExcept<T>(IEnumerable<T> seq, int indexToSkip) 
     { 
      return 
       from item in seq.Select((value, index) => new {value, index}) 
       where item.index != indexToSkip 
       select item.value; 
     } 
    } 
} 

如果您在输入重复的字符串,并要消除重复排列在输出中,然后使用DistinctBy()originally written by Jon Skeet),像这样:

var uniquePerms = Permute(items).DistinctBy(p => string.Join(" ", p)); 

其中DistinctBy()IEnumerable<T>的扩展方法:

public static class EnumerableExt 
{ 
    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) 
    { 
     return source.DistinctBy(keySelector, null); 
    } 

    public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
     this IEnumerable<TSource> source, 
     Func<TSource, TKey> keySelector, 
     IEqualityComparer<TKey> comparer) 
    { 
     return distinctByImpl(source, keySelector, comparer); 
    } 

    static IEnumerable<TSource> distinctByImpl<TSource, TKey>(
     IEnumerable<TSource> source, 
     Func<TSource, TKey> keySelector, 
     IEqualityComparer<TKey> comparer) 
    { 
     var knownKeys = new HashSet<TKey>(comparer); 
     return source.Where(element => knownKeys.Add(keySelector(element))); 
    } 
} 
+0

Thanx工作,是你写的? –

+0

@MuratcanOguzhan我写了置换代码,但可枚举的扩展方法最初由Jon Skeet,我认为是他的MoreLinq项目的一部分:https://www.nuget.org/packages/MoreLinq.Source.MoreEnumerable.DistinctBy/ –

+0

谢谢@MatthewWatson,我很感激。 –

相关问题