2012-09-07 17 views
23

yo escribimos un código en AS3 lo que me permitió comprobar si un determinado número de cosas fuera cierto ...booleanos de adición (como número entero)

If (true + false + true + true + false + true + true < 4) 
{ 

} 

cuando intenté volver a escribir en C#, me dice que no puedo agregar tipo bool y bool. ¿Es la mejor manera de hacerlo reescribirlo así? ¿O hay algún trabajo más simple?

If ((true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) < 4) 
{ 

} 
+2

'public int Toint (bool b) {return b? 1: 0;} ' –

+0

@ L.B:' ToInt' existe como 'Convert.ToInt32' – porges

+0

http: // stackoverflow.com/questions/377990/elegantly-determine-if-more-than-one-boolean-is-true –

Respuesta

47

Trate de usar IEnumerable<T>.Count(Func<T,bool>) de System.Linq, con T como bool, en un params parámetro de método.

public static int CountTrue(params bool[] args) 
{ 
    return args.Count(t => t); 
} 

Uso

// The count will be 3 
int count = CountTrue(false, true, false, true, true); 

También puede introducir un método this extensión:

public static int TrueCount(this bool[] array) 
{ 
    return array.Count(t => t); 
} 

Uso

// The count will be 3 
int count = new bool[] { false, true, false, true, true }.TrueCount(); 
+1

¡Bonito! Código muy limpio y elegante! – Mithrandir

+1

Eso es hermoso: ') ¡Gracias, esto es lo que usaré! – Randomman159

+3

+1 Sí, buena idea usando 'params' – sloth

13

Se puede crear una matriz y utilizar Count:

if ((new []{true, false, true, true, false, true, true}).Count(x=>x) < 4) 
{ 

} 

o la Sum método:

if ((new []{true, false, true, true, false, true, true}).Sum(x=>x?1:0) < 4) 
{ 

} 
+0

Si lo estuviera usando como una opción única, así es como lo haría, gracias a montones por responder * upvotes * – Randomman159

+0

Gracias! Este fue mi enfoque favorito. Tenía unos bools que necesitaba agregar así, y (new [] {var1, var2, var3, var4}). Sum (x => x? 1: 0); funcionó muy bien para mí! – statue

1

Convert.ToInt32(true) + Convert.ToInt32(false) + Convert.ToInt32(true) también trabajar en este caso creo que esto es mucho más simple que tenemos

+0

lo que dices al respecto –

11

He aquí un ejemplo más divertido:

if ((BoolCount)true + false + true + true + false + true + true <= 5) 
{ 
    Console.WriteLine("yay"); 
} 

El uso de esta clase:

struct BoolCount 
{ 
    private readonly int c; 
    private BoolCount(int c) { this.c = c; } 

    public static implicit operator BoolCount(bool b) 
     { return new BoolCount(Convert.ToInt32(b)); } 

    public static implicit operator int(BoolCount me) 
     { return me.c; } 

    public static BoolCount operator +(BoolCount me, BoolCount other) 
     { return new BoolCount(me.c + other.c); } 
} 
+1

¡Ja! Totalmente divertido, de hecho! +1 – sloth

0

(Inspirado por LB : s comentario) usted podría escribir un método de extensión:

static class Ex 
{ 
    public static int Int(this bool x) { return x ? 1 : 0; } 
} 

Y entonces (siempre y cuando incluya una using al espacio de nombres que contiene la clase Ex), se puede escribir el comunicado if así:

if (true.Int() + false.Int() + true.Int() + true.Int() + 
    false.Int() + true.Int() + true.Int() < 4) 
{ 
    ... 
} 
0

Se puede escribir un método de extensión para la clase BitArray. No estoy seguro de si el rendimiento sería mejor que el uso de LINQ, pero al menos es otra opción:

public static int CountSetBits(this BitArray theBitArray) 
{ 
    int count = 0; 
    for (int i = 0; i < theBitArray.Count; i++) 
    { 
     count += (theBitArray.Get(i)) ? 1 : 0; 
    } 
    return count; 
} 

Uso:

BitArray barray = new BitArray(new [] { true, true, false, true }); 
int count = barray.CountSetBits(); // Will return 3