Reputation: 93
In my current app I have 6 players and everyone has 1 boolean variable. Which under certain circumstances are set to true (originally they are false).. The problem is that I want to check which 5 variables are set to true and which one is set to false but I can't come up with any good idea.. only some if statements checking every single combination
if(a && b && c && d && e && !f)
{
//f is false in this case and I will do some operations here
}
However this is the ugliest and not well written code ever. What would be more general way of doing it?
Upvotes: 0
Views: 3894
Reputation: 32694
You're going to have a hard time doing this with just booleans. But if you wrap the boolean in a class with some other data, it becomes easier.
class Item
{
public bool IsCondition {get; set;}
public string Name {get; set;}
}
var itemsToCheck = new List<Item>()
{
new Item { IsCondition = true; Name = "A",
new Item { IsCondition = true; Name = "B",
new Item { IsCondition = false; Name = "C",
new Item { IsCondition = true; Name = "D",
}
foreach(var item in itemsToCheck)
{
if(!Item.IsCondition)
{
Console.WriteLine($"Item {item.Name} is false");
}
}
You can also get a list of all those that are false with Linq
var items = itemsToCheck.Where(i => !i.IsCondition);
Or if you know there will only ever be one that is false, you can get that single item.
var item = itemsToCheck.Where(i => !i.IsCondition).Single();
So there's two takeaways from this:
Upvotes: 5
Reputation: 12196
Using LINQ and List/Array will greatly reduce your code.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var players = new List<Player>
{
new Player("Orel", true),
new Player("Zeus"),
new Player("Hercules", true),
new Player("Nepton"),
};
var playingPlayers = players.Where(p => p.IsPlaying);
foreach (var player in playingPlayers)
{
Console.WriteLine(player.Name);
}
}
}
public class Player
{
public string Name { get; set; }
public bool IsPlaying { get; set; }
public Player(string name, bool isPlaying = false)
{
Name = name;
IsPlaying = isPlaying;
}
}
Upvotes: 0
Reputation: 100527
Normally you'd use array/list and just count false
values:
var onlyOneFromListIsFalse = players.Select(p => !p.SomeProperty).Count() == 1;
You can use similar approach with individual variables
var onlyOneVariableIsFalse = ((a ? 0 : 1) + (b ? 0 : 1) ... (f ? 0 : 1)) == 1;
Upvotes: 1
Reputation: 19149
You can assign them boolean list and then work with them.
List<bool> bools = new List<bool> {a,b,c,d,e,f};
if (bools.Count(x => x) == 5) // if there are 5 true items
{
int index = bools.IndexOf(false); // index of false item
// do your things here.
}
Remember that indexes are 0 based. means that index 0 refers to first item.
Upvotes: 2