【问题标题】:Is it possible to enumerate for all permutations of two IEnumerables using linq是否可以使用 linq 枚举两个 IEnumerables 的所有排列
【发布时间】:2010-04-13 13:05:19
【问题描述】:

我可以使用循环来做到这一点,但是有没有办法获取两个 IEnumerable,枚举所有可能的排列并选择一个包含排列的对象?我觉得这“应该”是可能的,但不确定要使用什么运算符。

谢谢 詹姆斯

【问题讨论】:

    标签: c# linq ienumerable permutation


    【解决方案1】:

    您是在谈论基本的笛卡尔连接吗?你可以做类似的事情

    var query = from item1 in enumerable1
                from item2 in enumerable2
                select new { Item1 = item1, Item2 = item2 }
    

    【讨论】:

    • 这可能是获得所有排列的方法 - 请记住它是 O(n*m)。但是,如果您只想要一个排列(比如随机排列),最好在每个列表上使用 ElementAt() 并使用随机索引来生成排列。
    【解决方案2】:

    Anthony's answer 是正确的。等效的扩展方法是:

    var query = enumerable1.SelectMany(
                    x => enumerable2,
                    (item1, item2) => new { Item1 = item1, Item2 = item2 }
                );
    

    var query = enumerable1.SelectMany(
                    item1 => enumerable2.Select(item2 => 
                        new { Item1 = item1, Item2 = item2 });
                );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-31
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多