Transform a DataTable into Dictionary C#

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

    i prefer this method:

    public static List> GetDataTableDictionaryList(DataTable dt)
    {
        return dt.AsEnumerable().Select(
            row => dt.Columns.Cast().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
        }
    }
    

提交回复
热议问题