2015-12-13 78 views
0

在我目前的应用程序中,我有6个玩家,每个人都有1个布尔变量。在某些情况下,它被设置为true(原来它们是错误的)。问题是我想检查哪5个变量设置为true,哪个设置为false,但我不能提出任何好主意。 。只有一些if语句检查每一个组合检查多个布尔变量是否具有特定值

if(a && b && c && d && e && !f) 
{ 
    //f is false in this case and I will do some operations here 
} 

然而,这是最丑的和写得不好过的代码。什么是更一般的做法呢?

+0

你能发布里面有布尔属性的类+一些执行代码吗? –

回答

4

你将很难用布尔值来做这件事。但是如果你用一些其他的数据包装布尔类,它就变得更容易了。

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"); 
    } 
} 

您还可以得到所有那些都是假的LINQ

var items = itemsToCheck.Where(i => !i.IsCondition); 

或者,如果你知道有只将永远是一个那是假的,你可以得到单个项目的列表。

var item = itemsToCheck.Where(i => !i.IsCondition).Single(); 

所以这是从这两外卖:

  • 您应该存储集的集合,在类似的数据作为一个列表
  • 使用一类这样的,当你需要把一些信息一起。
+0

感谢您的快速回答!这将完成这项工作,我会将此标记为答案。 – QuestionsEverywhere

2

您可以为它们分配布尔列表,然后使用它们。

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. 
} 

请记住,索引是基于0的。意味着索引0指的是第一项。

1

通常你会使用数组/列表,算了算false值:

var onlyOneFromListIsFalse = players.Select(p => !p.SomeProperty).Count() == 1; 

您可以使用单个变量

var onlyOneVariableIsFalse = ((a ? 0 : 1) + (b ? 0 : 1) ... (f ? 0 : 1)) == 1; 
0

类似的方法使用LINQ和列表/阵列将大大降低您的码。

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; 
    } 
} 
相关问题