如何使用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: !=,!=
答案 0 :(得分:2)
事实证明这比看起来更难,但以下内容应证明这一想法。
有两个步骤 - 创建每个运算符的数组列表对及其反向,然后递归地将它们置换在一起。
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?
答案 1 :(得分:0)
from operator in arrSample select operator + "," + ReverseOperator(operator)
或者我错过了什么?
答案 2 :(得分:0)
你想要一个工会吗?
string[] arrSample = new string[]{"!=","="};
var list = (
from item in arrSample
select item + "," + item
).Union(
from revItem in arrSample
select revItem + "," + ReverseOperator(revItem)
);
List<string> final = new List<string>(list);
答案 3 :(得分:0)
请找到具有不同组合的两个字符串数组的以下最简单方法
string [] roles = {&#34; abc&#34;,&#34; e&#34;,&#34; f&#34;,&#34; h&#34; };
string [] allRoles = {&#34; a&#34;,&#34; b&#34;,&#34; c&#34;,&#34; abc&#34;,&#34; e& #34;,&#34; f&#34;,&#34; g&#34;,&#34; h&#34;,&#34; i&#34; };
foreach (string nextRole in allRoles)
{
if (Array.IndexOf(roles, nextRole) != -1)
{
Response.Write(nextRole + "<br/>");
}
}