Transform a DataTable into Dictionary C#

半腔热情 提交于 2019-12-02 21:53:58

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.

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!

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));
}

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
    }
}

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));

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;
    }

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