Linq type conversion on generic types

2019-07-03 22:23发布

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?

3条回答
2楼-- · 2019-07-03 23:16

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();
查看更多
闹够了就滚
3楼-- · 2019-07-03 23:19

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] }
查看更多
叼着烟拽天下
4楼-- · 2019-07-03 23:23
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();
查看更多
登录 后发表回答