private void button1_Click(object sender, EventArgs e)
{
Dictionary<TextBox, string> map = new Dictionary<TextBox, string>();
Dictionary<TextBox, string> mapT1 = new Dictionary<TextBox, string>();
Dictionary<TextBox, string> mapT2 = new Dictionary<TextBox, string>();
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
map.Add((c as TextBox), (c as TextBox).Text);
}
}
//复制map给mapT1,mapT2用于第二组合第三组比较
foreach (KeyValuePair<TextBox,string> key in map)
{
mapT1.Add(key.Key,key.Value);
mapT2.Add(key.Key,key.Value);
}
//模拟常数项
string[] s1 = { "1","2","3"};
string[] s2 = { "3","4","5"};
string[] s3 = { "4","5"};
//测试标记法
//使用foreach集合遍历后的标记是倒叙方式
//应为后续方法都是用foreach遍历,所以倒叙可以忽略
int[] fl = new int[map.Count()];//标记项
int k = map.Count();
int i = 0;//用于记录对比的连续性
foreach (KeyValuePair<TextBox,string> key in map)
{
k--;
if (s1.Where(s => s == key.Value).Count() > 0)
{
i++;
}
else { i = 0; }
if (i == s1.Length)//当i=s1的长度,证明是第一个连续项,并记录在标记项 {
fl[k] = 1;
fl[k + 1] = 1;
fl[k + 2] = 1;
}
}
k = map.Count(); i = 0;
//根据标记更改
foreach (KeyValuePair<TextBox, string> key in map)
{
k--;
if (fl[k] == 1)
{
key.Key.BackColor = Color.Red;
mapT1.Remove(key.Key);
mapT2.Remove(key.Key);
}
}
//第二次判定
//先清零标记项
for (int j = 0; j < fl.Length; j++)
{
fl[j] = 0;
}
//设置初始项,判定标记项
//如果第一组没执行,那么mapT1=map。如果执行了mapT1就是减值后的键值对。
k = mapT1.Count(); i = 0;
foreach (KeyValuePair<TextBox, string> key in mapT1)
{
k--;
if (s2.Where(s => s == key.Value).Count() > 0)
{
i++;
}
else { i = 0; }
if (i == s2.Length)
{
fl[k] = 1;
fl[k + 1] = 1;
fl[k + 2] = 1;
}
}
k = mapT1.Count(); i = 0;
//根据标记更改颜色
foreach (KeyValuePair<TextBox, string> key in mapT1)
{
k--;
if (fl[k] == 1)
{
key.Key.BackColor = Color.Red;
mapT2.Remove(key.Key);
}
}
//黄色更改标记
for (int j = 0; j < fl.Length; j++)
{
fl[j] = 0;
}
//应为要完全包含 我理解为也是需要连续的
k = mapT2.Count(); i = 0;
foreach (KeyValuePair<TextBox,string> key in mapT2)
{
k--;
if (s3.Where(s => s == key.Value).Count() > 0)
{
i++;
}
else { i = 0; }
if (i == s3.Length)
{
fl[k] = 1;
fl[k + 1] = 1;
fl[k + 2] = 1;
}
}
k = mapT2.Count(); i = 0;
//黄色输出
foreach (KeyValuePair<TextBox, string> key in mapT2)
{
k--;
if (fl[k] == 1)
{
key.Key.BackColor = Color.Yellow;
}
}
}
测试通过了,代码没有整理,直接把测试的代码发上来了,重复的代码很多。
我也是C#的初学者,对集合的用法理解不深。需要用标记法解决问题。
请教关于String.Where(s => s == key.Value).Count这样的表达式。具体是怎么解释的呢?