c# - 数组组合的数组

标签 c# linq

如何使用 LinQ/C# 生成相反值的各种组合 我有一个数组中的运算符列表,例如 "> < = + ="我还有一个函数可以返回数组中每个项目的相反值。 ">" 的相反值是 "<"等等。因此考虑每个值的反向运算符如何生成各种可能的组合

示例: 问题陈述:

`string[] arrSample = new string[]{"!=","="};` //arrSample can be any object array with property values.The property can accept operator values like 
!=,=,>,< etc..

预期输出: 考虑反向运算符的各种组合将是

Output Sequence1: =,!=
Output Sequence2: !=,=
Output Sequence3: = , =
Output Sequence4: !=,!=

最佳答案

事实证明这比看起来更难,但下面应该演示这个想法。

有两个步骤 - 创建每个运算符及其反向的数组列表对,然后递归地将它们排列在一起。

void DoProblem()
{
    //string[] arrSample = new string[] { "!=", "=" };
    string[] arrSample = new string[] { "!=", "<","+" };

    string[][] arrPairs = (from op in arrSample select new string[]{op, GetReverse(op)}).ToArray();

    List<Array> myList = new List<Array>();
    myList.AddRange(arrPairs);

    foreach (string x in Permute(0, myList))
    {
        Console.WriteLine(x);
    }

}

List<string> Permute(int a, List<Array> x)
{
    List<string> retval = new List<string>();
    if (a == x.Count)
    {
        retval.Add("");
        return retval;
    }
    foreach (Object y in x[a])
    {
        foreach (string x2 in Permute(a + 1, x))
        {
            retval.Add(y.ToString() + "," + x2.ToString());
        }

    }
    return retval;
}


string GetReverse(string op)
{
    switch (op) {
        case "=":
            return "!=";
        case "!=":
            return "=";
        case "<":
            return ">";
        case "+":
            return "-";    
        default:
            return "";
    }
}

注意:排列函数基于排列数组的数组答案:C# Permutation of an array of arraylists?

关于c# - 数组组合的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5777208/

相关文章:

c# - 如何在 Visual Studio C# 中制作图表动画?

c# - 将引用传递给集合元素

c# - 将参数传递给模态数据

c# - 不明确的 IQueryable<T>.Where 和 IEnumerable<T>.Where 扩展方法

c# - Visual Studio 中 C# 字符串的语法和拼写检查器?

c# - 使用通用代码从 C# 中的另一个对象构建对象

vb.net - LINQ 中的 Where 子句与 Vb 中的 IN 运算符

c# - 从列表中删除相似条目

c# - Entity Framework : Update inside LINQ query

C# 数据表 LINQ 动态 row.field<datatype> 需要编码