-1

I have this :

  • Cat = 1 Dog = 2 Mouse = 4 House = 8 Ball = 16 Music = 32

And if i am getting an value from SQL = 3 -I want the output as "Cat, Dog" If value = 7 then "Cat, Dog, Mouse" and soo on.

Any help?

4

3 回答 3

2

http://ideone.com/aPqPqE

[System.Flags]
enum Things { Cat = 1, Dog = 2, Mouse = 4, House = 8, Ball = 16, Music = 32 }

class Program
{

    static void Main()
    {

        var value = Things.Cat | Things.Dog;

        Console.WriteLine(value.ToString());
     }
}
于 2013-09-14T04:10:57.973 回答
0

假设我们有enum Item = { Cat = 1, ... }

StringBuilder sb = new StringBuilder();

foreach(Item i in Enum.GetValues(typeof(Item))) 
    if ((valueFromSQL & ((int)i)) != 0) {
        if (sb.Length > 0)
            sb.Append(", ");
        sb.Append(i);
    }

string result = sb.ToString();

这可以正确处理零值和单个值(例如valueFromSQL = 4)。它之所以有效,是因为值的位表示如下:

Name          Decimal   Binary

Cat           1         ...0001
Dog           2         ...0010
Mouse         4         ...0100
valueFromSQL  3         ...0011

请注意,每个Item值仅使用一个唯一位。当您添加这些值时,您可以有效地将这些位 OR 在一起。因此,我们可以使用按位与来测试特定值的位是否非零。

于 2013-09-14T03:44:51.933 回答
-3

您可以使用 linq where 检查数字是否小于或等于指定值。

Dictionary<int, string> wordList = new Dictionary<int, string> {
            {1, "Cat"},
            {2, "Dog"},
            {4, "Mouse"},
            {8, "House"},
            {16, "Ball"},
            {32, "Music"},
        };

        int number = 7;

        StringBuilder builder = new StringBuilder();
        foreach (KeyValuePair<int, string> word in 
            wordList.Where(pair => pair.Key <= number)) {
            builder.Append(word.Value);
            builder.Append(", ");
        }
于 2013-09-14T03:59:40.433 回答