Linq类型转换通用类型 [英] Linq type conversion on generic types

查看:330
本文介绍了Linq类型转换通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码,我发现,但它不工作即使我尝试了许多转换。 。基本上,它巧妙地转换数据表到一个列表,可以序列化

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,GridBindingData的数据属性必须有一个列表<对象> 。这可能吗?

推荐答案

嗯。这是不容易看到你做了什么错误,但也许你需要 .Cast<对象>()了ToList()

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



修改这应该工作得很好,在REPL测试:

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] }

这篇关于Linq类型转换通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆