我正在尝试创建一个简单的计算器,以显示哪些数据包含在两个数组中,所有数字都由用户输入。我如何得到完整的数字因为我认为当我做foreach循环时读取数字,例如49,它读取为4和9而不是49?我如何解决这个问题?我错在哪里?
string firstTextBox = ConjTextBox.Text;
string secondTextBox = DisjTextBox.Text;
int intsInFirstTextBox;
int intsInSecondTextBox;
List<int> ListOfInts = new List<int>();
try
{
foreach (char c in firstTextBox)
{
intsInFirstTextBox = Convert.ToInt32(c);
foreach (char q in secondTextBox)
{
intsInSecondTextBox = Convert.ToInt32(q);
if (intsInFirstTextBox == intsInSecondTextBox)
{
ListOfInts.Add(intsInFirstTextBox);
ListOfInts.Sort();
}
}
}
foreach (int i in ListOfInts)
{
resultTextBox.Text += i.ToString();
}
}
catch (Exception Error)
{
resultTextBox.Text = Error.Message;
}
答案 0 :(得分:1)
char separator=',';
int temp=-1;
var list1=firstTextBox.Split(new char[]{separator})
.Where(n=>int.TryParse(n,out temp))
.Select(n=>temp);
var list2=secondTextBox.Split(new char[]{separator})
.Where(n=>int.TryParse(n,out temp))
.Select(n=>temp);
var common=list1.Intersect(list2);
答案 1 :(得分:0)
如果它们以逗号分隔,则拆分字符串然后循环遍历数组
char[] split = new char[] { ',' };
StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries;
string[] first = ConjTextBox.Text.Split(split, options);
string[] second = DisjTextBox.Text.Split(split, options);
int[] intsInFirstTextBox = Array.ConvertAll(first, s => int.Parse(s));
int[] intsInSecondTextBox = Array.ConvertAll(second, s => int.Parse(s));
int[] ListOfInts = intsInFirstTextBox.Intersect(intsInSecondTextBox);