泛型类型的Linq类型转换

时间:2011-11-20 21:35:45

标签: c# linq telerik-grid

我找到了这个代码,但即使我尝试了很多转换后它也无法正常工作。基本上它巧妙地将Datatable转换为可序列化的List。

错误在于它无法将Dictionary<string, object>转换为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 };
}

我尝试过多次转换,包括:

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

基本上,GridBindingData的Data属性必须有List<object>。这可能吗?

3 个答案:

答案 0 :(得分:6)

嗯。要看到你得到的错误并不容易,但也许你需要.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();

编辑这应该完美无缺,在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] }

答案 1 :(得分:0)

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

答案 2 :(得分:0)

答案取决于你对结果的要求:字典键,值,两者?

假设您希望将值作为对象,则应执行此操作:

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