Linq type conversion on generic types

强颜欢笑 提交于 2019-12-12 14:06:10

问题


I have this code I found but it doesnt work even after i tried many conversions. Basically it converts smartly a Datatable into a List that can be serializable.

The error is that it can't convert a Dictionary<string, object> to a List<object>:

public GridBindingData GetSomething() {

DataTable dt = GetDatatable();

var columns = dt.Columns.Cast<System.Data.DataColumn>();

var data = dt.AsEnumerable()
    .Select(r => columns.Select(c => new { Column = c.ColumnName, Value = r[c] })
    .ToDictionary(i => i.Column, i => i.Value != System.DBNull.Value ? i.Value : null))
    .ToList<object>();

return new GridBindingData() { Data = data , Count = dt.Rows.Count };
}

I tried many conversions including:

List<object> newdata = (List<object>)data.AsEnumerable().Cast<object>();

Basicaly, the Data property of GridBindingData must have a List<object>. Is that possible?


回答1:


Mmm. It's not easy to see what error you are getting, but perhaps you need .Cast<object>().ToList():

var data = dt.AsEnumerable()
    .Select(r => columns.Select(c => new { Column = c.ColumnName, Value = r[c] })
    .ToDictionary(i => i.Column, i => i.Value != System.DBNull.Value ? i.Value : null))
    .Cast<object>()
    .ToList();

Edit this should work flawlessly, tested in the REPL:

csharp> new Dictionary<string, string> { {"key","value"} }.ToList().Cast<object>();
{ [key, value] }

csharp> new Dictionary<string, string> { {"key","value"} }.Cast<object>().ToList();               
{ [key, value] }



回答2:


data = dt.AsEnumerable()
    .Select(r => columns.Select(c => new { Column = c.ColumnName, Value = r[c] })
    .ToDictionary(i => i.Column, i => i.Value != System.DBNull.Value ? i.Value : null))
    .Select(x => (object)x)
    .ToList();



回答3:


The answer depends on what you want for your results: the dictionary keys, the values, both?

Assuming you want the values as objects, this should do it:

data = dt.AsEnumerable()
    .Select(r => columns.Select(c => new { Column = c.ColumnName, Value = r[c] })
    .ToDictionary(i => i.Column, i => i.Value != System.DBNull.Value ? i.Value : null))
    .Select(x => (object)x.Value)
    .ToList();


来源:https://stackoverflow.com/questions/8204930/linq-type-conversion-on-generic-types

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