Hello,
The basic idea for checking many bool values is with the .Any extension. The following code samples were done with VS2019, C# 9, .NET 5.
- Button one is against a bool array
- Button two is against a property in a list of a class named Item
- Button three is against CheckBox controls directly on a form
- BooleanExtensions is for demo purposes only
- I used three items in each demo but the number can be any number greater than 1 to work.
Code
For a real app, Item class and BooleanExtensions class would be in their own class files.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
namespace BoolCheck
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool[] values1 = {true, false, true};
Debug.WriteLine(values1.Any(booItem=> booItem is false) ?
"Not all true" :
"All true");
values1 = new[] { true, true, true };
Debug.WriteLine(values1.Any(boolItem => boolItem is false) ?
"Not all true" :
"All true");
}
private void button2_Click(object sender, EventArgs e)
{
var items = new List<Item>
{
new() {Id = 1, Vlc = true},
new() {Id = 2, Vlc = false},
new() {Id = 3, Vlc = true}
};
Debug.WriteLine(items.Any(item => item.Vlc is false) ?
"Not all true" :
"All true");
var notTrueItems = items
.Select((item, index) => new {Item = item, Index = index})
.Where(data => data.Item.Vlc is false)
.ToList();
for (int index = 0; index < notTrueItems.Count; index++)
{
notTrueItems[index].Item.Vlc = true;
}
Debug.WriteLine(items.Any(item => item.Vlc is false) ?
"Not all true" :
"All true");
}
private void button3_Click(object sender, EventArgs e)
{
var checkBoxes = !Controls.OfType<CheckBox>().Any(cb => cb.Checked is false);
Debug.WriteLine($"CheckBoxes all checked?: {checkBoxes.ToYesNoString()}");
}
}
public class Item
{
public int Id { get; set; }
public bool Vlc { get; set; }
}
public static class BooleanExtensions
{
public static string ToYesNoString(this bool value) => value ? "Yes" : "No";
}
}