Transform a DataTable into Dictionary C#

前端 未结 8 1856
爱一瞬间的悲伤
爱一瞬间的悲伤 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:26

    i think this will help you:

                DataTable dt = new DataTable();
                dt.Columns.Add("Column1");
                dt.Columns.Add("Column2");
                dt.Rows.Add(1, "first");
                dt.Rows.Add(2, "second");
                var dictionary = dt.Rows.OfType<DataRow>().ToDictionary(d => d.Field<string>(0), v => v.Field<object>(1));
    
    0 讨论(0)
  • 2021-02-02 07:27

    All the previos answers didn't help me, so I did this:

    myList = dt.AsEnumerable()
    .ToDictionary<DataRow, string, string>(row => row[0].ToString(),
                                           row => row[1].ToString()); 
    

    and it worked great!

    0 讨论(0)
  • 2021-02-02 07:27

    Visual basic
    Using sql to load a datatable and create a dictionary

        Dim SalesRep As New System.Collections.Generic.Dictionary(Of String, String)(StringComparer.InvariantCultureIgnoreCase)
        Using tbl As New Data.DataTable("SalesRep")
            SqlCommand.CommandText = "Select Initial,FullName from QB_SalesRep"
            tbl.Load(SqlCommand.ExecuteReader())
            ' --- Option ONE use the array to iterate
            Array.ForEach(tbl.Rows.Cast(Of Data.DataRow).ToArray(),
                          Sub(f)
                              SalesRep.Add(f.ItemAsString("Initial"), f.ItemAsString("FullName"))
                          End Sub)
            ' --- Option TWO use plain linq to create the dictionary
            SalesRep = tbl.Rows _
                .Cast(Of Data.DataRow) _
                .AsEnumerable() _
                .ToDictionary(Function(f) f.Item("Initial").toString(), Function(f) f.Item("FullName").toString)
        End Using
    
    0 讨论(0)
  • 2021-02-02 07:36

    i prefer this method:

    public static List<Dictionary<string, string>> GetDataTableDictionaryList(DataTable dt)
    {
        return dt.AsEnumerable().Select(
            row => dt.Columns.Cast<DataColumn>().ToDictionary(
                column => column.ColumnName,
                column => row[column].ToString()
            )).ToList();
    }
    

    the reason why is because this code can also deal with Booleans or other data types by calling the ToString method.

    Notice this returns a list of dictionaries, you can modify it to a dictionary of dictionaries if you have key for each row.

    iterate over a bool column might look like so:

    var list = GetDataTableDictionaryList(dt);
    
    foreach (var row in list)
    {
        if (row["Selected"].Equals("true", StringComparison.OrdinalIgnoreCase))
        {
            // do something
        }
    }
    
    0 讨论(0)
  • 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<DataColumn>().ToDictionary(
                        // ...and find the key value pairs for the dictionary  
                        column => column.ColumnName,    // Key  
                        column => row[column] as string // Value  
                        )
                    ).ToList();
        }
    
        public static List<Dictionary<string, object>> DataTableToDictionaryList(DataTable dt)
        {
            var result = new List<Dictionary<string, object>>();
            //or var result = new List<Dictionary<string, string>>();
    
            foreach (DataRow row in dt.Rows)
            {
                var dictRow = new Dictionary<string, object>();
                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;
        }
    }  
    
    0 讨论(0)
  • 2021-02-02 07:38

    The generic method ToDictionary has 3 parameters. You left one off, so it doesn't know what to do. If you want to specify all of the parameters, it would be <DataRow, string, object>.

    internal Dictionary<string,object> GetDict(DataTable dt)
    {
        return dt.AsEnumerable()
          .ToDictionary<DataRow, string, object>(row => row.Field<string>(0),
                                    row => row.Field<object>(1));
    }
    

    Of course, if you leave them off, the compiler is able to infer the types, so you don't get the error.

    0 讨论(0)
提交回复
热议问题