代码之家  ›  专栏  ›  技术社区  ›  XstreamINsanity

如何使用字符串作为索引?

  •  7
  • XstreamINsanity  · 技术社区  · 16 年前

    早晨。


    我有一门课叫报告。两个建筑工人。一个不允许参数,另一个是字符串数组。字符串数组应该是它们想要显示的报告。我想做的是:

    string strSQL = this.Queries[strReportName];
    

    我觉得这是可能的,因为在我使用的dataGridView中,我通过以下方式获得列索引:

    int nColumnIndex = dgvParts.Columns[strColumnName].Index;
    

    这两个示例都使用一个字符串来确定它们检索的数组中的值,但我不确定如何执行此操作。有人能帮我吗?感谢所有的帮助。

    对于编辑和mods:是的,报告部分与我的另一篇关于动态加载dll的文章松散地联系在一起,但是我想保持另一篇文章的开放性。我的老板和我决定短期内,我们只会有一个单一的动态链接库,所有的东西都是硬编码的,但从长远来看,我们希望动态地将动态链接库作为报告,所以请不要标记为重复。我计划这个周末尝试并实现另一个线程中提供给我的方法。谢谢。

    编辑-问题的第2部分

    public class Queries
    {
      #region Report Queries
        #region Missing Code
          string strMissingCode = "SELECT * FROM PARTS WHERE CODE IS NULL OR CODE = ''";
        #endregion
      #endregion
    }
    

    我想把它改成这样:

    public class Queries : Dictionary<string, string>
    {
    }
    

    但我不希望他们必须使用构造函数来实例化它。我需要静态排序,这样我就可以运行这样的代码:

    class Reports
    {
      private List<ReportRecord> _lstRecrods = new List<ReportRecord>();
      public List<ReportRecord> Records { get { return _lstRecords; } }
    
      public Reports(string[] strDisplayedReports)
      {
        foreach (string strReportTitle in strDisplayedReports)
        {
          this.BuildReportList(strReportTitle);
        }
      }
    
      private void BuildReportList(string strReportTitle)
      {
        using (DataSet ds = Database.GetDataSet(Queries[strReportTitle]))
        {
          ...
        }
      }
    }
    

    如何使其静态排序到不必实例化查询的位置?谢谢各位。

    6 回复  |  直到 16 年前
        1
  •  10
  •   Ignacio Vazquez-Abrams    16 年前

    Dictionary 可以使用字符串作为“索引”(实际上是键)。

        2
  •  14
  •   Patrick McDonald    16 年前

    我想你在找以下的东西:

    public class Reports
    {
        System.Collections.Generic.IDictionary<string,string> queries;
    
        public string this[string key]
        {
            get
            {
                return this.queries[key];
            }
        }
    }
    

    http://msdn.microsoft.com/en-us/library/aa288464(VS.71).aspx 更多信息。

    如果不需要向Reports类添加更多功能,那么只需像其他人发布的那样使用字典。

        3
  •  2
  •   Alex    16 年前
        4
  •  0
  •   epitka    16 年前

    this.querys.SingleOrDefault(x=>x.Name==strReportName)不起作用?如果没有,您可以创建一个扩展方法,将此代码隐藏在索引器[]中

        5
  •  0
  •   Chinjoo    16 年前

    你可以用数组.IndexOf(这个。查询,strReportName);

        6
  •  -2
  •   KP.    16 年前

    c#中的基本数组是基于索引的,不能使用字符串访问器。

    这样做有效:

    string[] someArray = {"query 1", "query 2"};
    string myQuery = someArray[1];
    

    这并不意味着:

    myQuery = someArray["some value"];
    

    使用 Dictionary 类,它允许任何类型的键,包括复杂类型。