Transform a DataTable into Dictionary C#

前端 未结 8 1855
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 07:13

I want to know how to transform a DataTable into a Dictionary. I did something like this.

using System.Linq;

internal Dictionary GetDict(Da         


        
8条回答
  •  攒了一身酷
    2021-02-02 07:37

    Given solutions assume only 2 columns. In case you want multi column representation, you need a list of dictionary

    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Column1");
            dt.Columns.Add("Column2");
            dt.Columns.Add("Column3");
            dt.Rows.Add(1, "first", "A");
            dt.Rows.Add(2, "second", "B");
    
            var dictTable = DataTableToDictionaryList(dt);
            var rowCount = dictTable.Count;
            var colCount = dictTable[0].Count;
    
            //Linq version
            var dictTableFromLinq = dt.AsEnumerable().Select(
                    // ...then iterate through the columns...  
                    row => dt.Columns.Cast().ToDictionary(
                        // ...and find the key value pairs for the dictionary  
                        column => column.ColumnName,    // Key  
                        column => row[column] as string // Value  
                        )
                    ).ToList();
        }
    
        public static List> DataTableToDictionaryList(DataTable dt)
        {
            var result = new List>();
            //or var result = new List>();
    
            foreach (DataRow row in dt.Rows)
            {
                var dictRow = new Dictionary();
                foreach (DataColumn col in dt.Columns)
                {
                    dictRow.Add(col.ColumnName, row[col]);
                    //or dictRow.Add(col.ColumnName, row[col].ToString());
                }
    
                result.Add(dictRow);
            }
    
            return result;
        }
    }  
    

提交回复
热议问题