多维数组和

时间:2013-09-14 03:31:12

标签: c# asp.net arrays multidimensional-array delegates

我有这个:

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

如果我从SQL = 3获取值 - 我希望输出为“Cat,Dog” 如果值= 7那么“猫,狗,老鼠” 和soo。

任何帮助?

3 个答案:

答案 0 :(得分: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());
     }
}

答案 1 :(得分: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组合在一起。因此,我们可以使用按位AND来测试特定值的位是否为非零。

答案 2 :(得分:-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(", ");
        }