-->

Linq type conversion on generic types

2019-07-03 23: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();