Skip to main content
 首页 » 编程设计

c#之如何为我的场景替换 if 循环逻辑

2024年02月24日18sky-heaven

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

使用上面的(如表)将获取给定 header 值的值。 例如:if(column="A"&& row = "B1") 那么 value="4"

在不经常使用 if 循环的情况下,是否有使用 C# 获取值的想法。

注意:以上不是从数据库或任何内存对象获取的表或结构。它只是给定 header 值的值映射。

请您参考如下方法:

最简单的解决方案可能是使用 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]; 
    } 
}