检查文本框是否与其他文本框具有相同的值
本文关键字:文本 其他 是否 检查 | 更新日期: 2023-09-27 18:32:30
我想检查我的文本框中是否有类似的值,我有 10 个文本框,单击按钮时我想验证是否有相同的值
for (int c = 1; c <= 10; c++)
{
TextBox check_subjName = table_textboxes.FindControl("subject_name" + c.ToString()) as TextBox;
for (int b = 1; b <= 10; b++)
{
TextBox check_subjName2 = table_textboxes.FindControl("subject_name" + b.ToString()) as TextBox;
if (c != b)
{
if (check_subjName.Text == check_subjName2.Text)
{
//there are similar values
}
}
}
}
因此,
如果所有文本框具有不同的值,则它是有效的。您可以使用 LINQ:
List<string> textList = table_textboxes.Controls.OfType<TextBox>()
.Where(txt => txt.ID.StartsWith("subject_name"))
.Select(txt => txt.Text.Trim())
.ToList();
var distinctTexts = new HashSet<string>(textList);
bool allDifferent = textList.Count == distinctTexts.Count;
这里有一个稍微优化的方法(在本例中为微优化):
var textList = table_textboxes.Controls.OfType<TextBox>()
.Where(txt => txt.ID.StartsWith("subject_name"))
.Select(txt => txt.Text.Trim());
HashSet<string> set = new HashSet<string>();
bool allDifferent = textList.All(set.Add);