【问题标题】:Create Combination of list of value in C#.net在 C#.net 中创建值列表的组合
【发布时间】:2017-03-25 12:48:06
【问题描述】:

我的 C# 程序中有一个字符串列表。但是,我只在运行时才知道列表中的项目数。

假设,为了简单起见,我的列表是 {{F1, F2, F3},{P1, P2},{A1, A2, A3}} 现在我需要生成所有可能的组合,如下所示。

下面是我列表的图片

{F1 P1 A1}, {F1 P1 A2}, {F1 P1 A3}, {F1 P2 A1}, {F1 P2 A2}, {F1 P2 A3}, {F2 P1 A1}, {F2 P1 A2} , {F2 P1 A3}, {F2 P2 A1} {F2 P2 A2}, {F2 P2 A3}, {F3 P1 A1}, {F3 P1 A2}, {F3 P1 A3},{F3 P2 A1}, {F3 P2 A2}, {F3 P2 A3}

有人可以帮忙吗?

【问题讨论】:

  • 每个子列表中的值是否(例如{A1, A2, A3}不同
  • 不,它不是子列表。例如。我有字符串列表。 List[0] 将是 {F1, F2, F3}。列表[1] = {P1, P2} 和列表[2] = {A1, A2, A3}。我更新了我的问题并添加了一张图片,以便帮助您理解它

标签: c# combinations


【解决方案1】:
基于

Linq 的解决方案(前提是该列表没有 nullempty 子列表,并且每个子列表中的所有值都被视为唯一/不同) :

private static IEnumerable<List<T>> MyEnumerator<T>(List<List<T>> data) {
  List<int> indexes = Enumerable.Repeat(0, data.Count).ToList();

  do {
    yield return indexes
      .Select((value, i) => data[i][value])
      .ToList();

    for (int i = data.Count - 1; i >= 0; --i)
      if (indexes[i] == data[i].Count - 1)
        indexes[i] = 0;
      else {
        indexes[i] += 1;

        break;
      }
  }
  while (indexes.Any(value => value != 0));
}

测试:

  List<List<String>> data = new List<List<string>>() {
    new List<string> { "F1", "F2", "F3"},
    new List<string> { "P1", "P2"},
    new List<string> { "A1", "A2", "A3"},
  };

  var result = MyEnumerator(data).Select(list => "{" + string.Join(", ", list) + "}");

  Console.Write(string.Join(Environment.NewLine, result));

结果:

{F1, P1, A1}
{F1, P1, A2}
{F1, P1, A3}
{F1, P2, A1}
{F1, P2, A2}
{F1, P2, A3}
{F2, P1, A1}
{F2, P1, A2}
{F2, P1, A3}
{F2, P2, A1}
{F2, P2, A2}
{F2, P2, A3}
{F3, P1, A1}
{F3, P1, A2}
{F3, P1, A3}
{F3, P2, A1}
{F3, P2, A2}
{F3, P2, A3}

编辑:如果你碰巧有一个 逗号分隔的字符串列表

  List<string> source = new List<string> {
    "F1,F2,F3",
    "P1,P2",
    "A1,A2,A3",
  };

您可以通过一个 Linq 获得所需的List&lt;List&lt;string&gt;&gt;

  List<List<String>> data = source
    .Select(line => line
       .Split(',')
       .Distinct()
       .ToList())
    .ToList();

  var result = MyEnumerator(data).Select(list => "{" + string.Join(", ", list) + "}");

  Console.Write(string.Join(Environment.NewLine, result));

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多