如何替换我的场景的if循环逻辑?

时间:2010-11-17 07:02:22

标签: c# c#-3.0

    A   B   C
A1  1   2   3
B1  4   5   6
C1  7   8   9

使用上面的(如表)来获取给定标头值的值。 例如:if(column =“A”&& row =“B1”)则value =“4”

不使用常常的if循环,是否有任何想法使用C#获取值。

注意:以上不是获取表单DB或任何内存对象的表或结构。它只是给定标头值的值映射。

2 个答案:

答案 0 :(得分:2)

你可以拥有Dictionary<Tuple<string, string>, int>;见Tuple。您需要确定这是否适合您。

答案 1 :(得分:2)

最简单的解决方案可能是使用Dictionary<Tuple<string, string>, int>,假设您使用的是.NET 4.它的工作原理如下:

private readonly Dictionary<Tuple<string, string>, int> Table = 
    new Dictionary<Tuple<string, string>, int>
{
    { Tuple.Create("A1", "A"), 1 },
    { Tuple.Create("A1", "B"), 2 },
    { Tuple.Create("A1", "C"), 3 },
    { Tuple.Create("B1", "A"), 4 },
    { Tuple.Create("B1", "B"), 5 },
    { Tuple.Create("B1", "C"), 6 },
    { Tuple.Create("C1", "A"), 7 },
    { Tuple.Create("C1", "B"), 8 },
    { Tuple.Create("C1", "C"), 9 },
};

public int this[string row, string column]
{
    get
    {
        return Table[Tuple.Create(row, column)];
    }
}

如果您不使用.NET 4,那么可以通过将行和列组合在一起来伪造它,例如通过连接它们并添加斜杠:“A / A1”,“B / B1”等,然后加Dictionary<string, int>。这很丑陋 - 我很想写自己的RowColumn结构来避免这种情况。

另一种方法是保留两个字典,每个字典将行名称或列名称映射到索引,然后为值设置int[,]数组。这样做的好处是,您可以识别行或列无效的时间。如果你真的只有几行或几列,一个简单的字符串列表可能会同样快或更快:

private readonly List<string> RowNames = new List<string> { "A1", "B1", "C1" };
private readonly List<string> ColumnNames = new List<string> { "A", "B", "C" };
private readonly int[,] Values = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

public int this[string row, string column]
{
    get
    {
        int rowIndex = RowNames.IndexOf(row);
        if (rowIndex == -1)
        {
            throw new ArgumentOutOfRangeException("Invalid row specified");
        }
        int columnIndex = ColumnNames.IndexOf(column);
        if (columnIndex == -1)
        {
            throw new ArgumentOutOfRangeException("Invalid column specified");
        }
        return Values[rowIndex, columnIndex];
    }
}