[英]Querying with a string converted from an array of ints, results in Conversion data type smallint error
[英]Best way to do conversion from IQueryable of a type to an array of a converted type?
我正在使用实体框架,并希望将IQueryable的元素放入转换类型的数组中。 将NormalType
作为第一种类型并将ConvertedType
作为转换后的类型,“转换”以这种方式完成:
//Creates a NormalType object based on ConvertedType instance.
NormalType nt = new NormalType (ctInstance);
// Returns a new ConvertedType instance,
//based on the content of the NormalType instance.
ConvertedType ct = nt.getConvertedType();
现在,我想将NormalType类型的列表转换为ConvertedType数组( IQueryable<NormalType> -> ConvertedType[]
)。
我的第一个想法是经典迭代IQueryable<NormalType>
,将数据放入List<ConvertedType>
,然后使用ToArray()
方法将第二个列表转换为数组:
//Rest of code....
List<ConvertedType> convertedTypeList = new List<ConvertedType>();
//normalTypeIQueryable is of type IQueryable<NormalType>
foreach(NormalType normalType in normalTypeIQueryable)
{
convertedTypeList.Add(normalType.getConvertedType());
}
ConvertedType[] convertedTypeArray = convertedTypeList.ToArray();
我的第二个想法是在一行中使用ToList()
, ConvertAll(...)
和ToArray()
:
normalTypeIQueryable.ToList().ConvertAll(n => n.GetConvertedType()).ToArray();
我认为最后一个将通过转换导致多个循环。
这两种方式中的哪一种在性能方面更好? 还有更好的选择吗?
先感谢您。
更新: GetConvertedType()
以“深层复制”方式基于NormalType
包含的数据创建转换类型的新实例。
这非常简单。 您要做的是将源序列中的值投影到不同的值中,然后将生成的序列放入数组中。
LINQ使用Select
投影,所以最简单,最自然,并且(至少只要你将使用LINQ)最有效的方式来编写它:
var result = input.AsEnumerable().Select(i => i.GetConvertedType()).ToArray();
这实际上等同于示例中的手动foreach
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.