What Should I use? a dictionary, list, or something else [closed]

放肆的年华 提交于 2020-02-23 08:28:20

问题


Please excuse the very entry-level nature of this question. I'm very new to c#.

When I work with various libraries and components that have objects stored in collections, I'm able to retrieve the object by either the object name or its index. I want to implement a similar collection in c#; however, my understanding is that

  • A dictionary returns a key value pair (the key and the object) and I only want it to return the object, not the key.
  • A list won't allow a lookup key.

I'm sure this is very basic but if someone could point me in the right direction then I would certainly appreciate it. See code example below:


        class CallingProgram
    {
        private void useColumn()
        {
            DataTable tbl = new DataTable();
            //I need a collection that can do this
            DataColumn col = new DataColumn();
            col = tbl.Columns["Column_1"];
            //and this
            col = tbl.Columns[0];
            //What I want to do and I've seen collections that work like this
            foreach(DataColumn colmn in tbl.Columns)
            {
                //foreach doesn't work because it returns a key/value pair
            }

            //What works, but I don't always want to the end user of the library
            //to always have to type '.Values'
            foreach (DataColumn colmn in tbl.Columns.Values)
            {
                //do something
            }
        }
    }

    public class DataTable
    {
        public string TableName { get; set; }
        public Dictionary<string, DataColumn> Columns { get; set; }

        public DataTable()
        {
            Dictionary<string, DataColumn> Columns = new Dictionary<string, DataColumn>();
            DataColumn col = new DataColumn();
            col.ColumnName = "Column_1";
            Columns.Add(col.ColumnName, col);
        }

    }

    public class DataColumn
    {
        public string ColumnName { get; set; }
        public string ColumnProperty { get; set; }
    }

来源:https://stackoverflow.com/questions/60347180/what-should-i-use-a-dictionary-list-or-something-else

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!