Transform a DataTable into Dictionary C#

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

    ToDictionary is expecting the IEnumberable<T> as the first type... you were telling it that it was a string which is wrong it's IEnumerable<DataRow>

    It's getting confused by you specifying the types... try this...

    internal Dictionary<string,object> GetDict(DataTable dt)
    {
        return dt.AsEnumerable()
          .ToDictionary(row => row.Field<string>(0),
                                    row => row.Field<object>(1));
    }
    
    0 讨论(0)
  • 2021-02-02 07:53

    I found the solution but don't know why. I edited my Question completing the code just for make it clear what I was doing an I changed to this

        internal Dictionary<string, object> GetDict(DataTable dt)
        {
            Dictionary<String, Object> dic = dt.AsEnumerable().ToDictionary(row => row.Field<String>(0), row => row.Field<Object>(1));
            return dic;
        }
    
    0 讨论(0)
提交回复
热议问题