如何将以下多个foreach
转换为LINQ?
foreach (var resourceOne in resourceList)
{
string s = (string)resourceOne;
foreach (Control c in gridBtn.Children)
{
if (c.GetType() == typeof(ToggleButton))
{
int TagPlusOne = Convert.ToInt32(c.Tag) + 1;
string PaddedResult = TagPlusOne.ToString().PadLeft(3, '0');
if (PaddedResult == s)
{
((ToggleButton)c).BorderBrush = Brushes.Red;
((ToggleButton)c).BorderThickness = new Thickness(3, 3, 3, 3);
}
}
}
}
答案 0 :(得分:2)
您确实不能,但是可以使用Where
和OfType
foreach (var in gridBtn.Children.OfType<ToggleButton>)
{
int TagPlusOne = Convert.ToInt32(c.Tag) + 1;
string PaddedResult = TagPlusOne.ToString().PadLeft(3, '0');
foreach (var resourceOne in resourceList.Where(x => x == PaddedResult))
{
c.BorderBrush = Brushes.Red;
c.BorderThickness = new Thickness(3, 3, 3, 3);
}
}
免责声明:完全未经测试(再次)
答案 1 :(得分:2)
IEnumerable<ToggleButton> query =
from c in gridBtn.Children
where c.GetType() == typeof(ToggleButton)
let tagPlusOne = Convert.ToInt32(c.Tag) + 1
let paddedResult = tagPlusOne.ToString().PadLeft(3, '0')
join s in resourceList.Cast<string>() on paddedResult equals s
select c;
foreach(ToggleButton button in query)
{
button.BorderBrush = Brushes.Red;
button.BorderThickness = new Thickness(3, 3, 3, 3);
}
答案 2 :(得分:0)
您可以执行以下操作(由于没有您的环境,我无法测试):
gridBtn.Children.Where(c =>
c.GetType() == typeof(ToggleButton) && resourceList.Any(resourceOne =>
(string) resourceOne ==
Convert.ToInt32(c.Tag) + 1.ToString().PadLeft(3, '0')))
.ToList().ForEach(c =>
{
((ToggleButton) c).BorderBrush = Brushes.Red;
((ToggleButton) c).BorderThickness = new Thickness(3, 3, 3, 3);
});
答案 3 :(得分:0)
最后,您需要使用foreach
或类似名称来设置按钮上的属性,因为LINQ是用于查询数据(通常无副作用),而不是变异他们。但是,您可以使用LINQ来简化查找您要编辑的按钮。例如您的代码可以归结为:
var targetButtons = gridBtn
.Children
.OfType<ToggleButton>()
.Where(tb => resourceList.OfType<string>().Contains($"{Convert.ToInt32(tb.Tag) + 1}:D3"));
foreach(var btn in targetButtons)
{
btn.BorderBrush = Brushes.Red;
btn.BorderThickness = new Thickness(3, 3, 3, 3);
}
可以进一步进行调整/优化/重构。请注意,我已将PadLeft(3, '0')
替换为具有相同功能的D3
标准数字格式字符串。
答案 4 :(得分:0)
您可以使用此代码。我为Buttons和WinForm测试了这样的代码。 希望代码对您有帮助。
resourceList.Where(resourceOne =>
{
string s = (string)resourceOne;
gridBtn.Children.OfType<ToggleButton>().Where(c =>
{
var TagPlusOne = Convert.ToInt32(c.Tag) + 1;
var PaddedResult = TagPlusOne.ToString().PadLeft(3, '0');
return PaddedResult == s;
}).ToList().ForEach(c =>
{
c.BorderBrush = Brushes.Red;
c.BorderThickness = new Thickness(3, 3, 3, 3);
});
return true;
});
我认为您也可以使用Select代替Foreach。
esourceList.Where(resourceOne =>
{
string s = (string)resourceOne;
var enumerable = ActiveForm.Controls.OfType<Button>().Where(control =>
{
var TagPlusOne = Convert.ToInt32(control.Tag) + 1;
var PaddedResult = TagPlusOne.ToString().PadLeft(3, '0');
return PaddedResult == s;
}).Select(control =>
{
control.BackColor = Color.Aqua;
control.Cursor = Cursors.WaitCursor;
return control;
});
return true;
});