在我的应用程序中,我有一个可能是int \ long \ short的未知类型列表。将未知长 int short转换为C中的两倍#
我需要将此列表转换为双精度。
什么是最快和最有效的方法来实现这一目标? (它需要尽可能快,因为它可以)
在我的应用程序中,我有一个可能是int \ long \ short的未知类型列表。将未知长 int short转换为C中的两倍#
我需要将此列表转换为双精度。
什么是最快和最有效的方法来实现这一目标? (它需要尽可能快,因为它可以)
我假设你有List<object>
,你需要将其转换为List<double>
试试这个,这将为所有工作实施IConvertible
的类型。 long
,int
,short
,float
等..
var doubleList = objectList.Select(x=> Convert.ToDouble(x)).ToList();
试试这个
List<double> doubleList = intList.ConvertAll(x => (double)x);
如果列表是类型对象:( –
@SriramSakthivel读取的问题只是要求'int \ long \ short'而不是'object' – Nilesh
您再次阅读该问题!**在我的应用程序中,我有一个在这种情况下,我得到一个未知类型的列表,它可以是int \ long \ short。**如果你不知道类型,那么你只能将类型存储在'List
奈斯利简单:
var doubleList = listOfObjects.Select(i => Convert.ToDouble(i)).ToList();
微优化,因为你说 “最高效” 是很重要的:
int count = listOfObjects.Count;
var doubleList = new List<double>(listOfObjects.Count);
for(int i = 0; i != count; ++i)
doubleList.Add(Convert.ToDouble(listOfObjects[i]));
然而,“最有效”取决于你需要的最有效率。你得到不同的效率与:
public class DoubleList : IList<double>
{
private readonly List<object> _source; // Change to IList<object> if that's a possibility
public DoubleList(List<object> source)
{
_source = _source;
}
// Hide half-supported implementation from main interface
double IList<double>.this[int index]
{
get { return Convert.ToDouble(_source[index]); }
set { throw new NotSupportedException("Read-only collection"); }
}
public double this[int index]
{
get { return Convert.ToDouble(_source[index]); }
}
public int Count
{
get { return _source.Count; }
}
bool ICollection<double>.IsReadOnly
{
get { return true; }
}
/* Lots of boring and obvious implementations skipped */
public struct Enumerator : IEnumerator<double>
{
// note, normally we'd just use yield return in the
// GetEnumerator(), and we certainly wouldn't use
// a struct here (there are issues), but this
// optimisation is in the spirit of "most efficient"
private List<object>.Enumerator _en; //Mutable struct! Don't make field readonly!
public double Current
{
get { return Convert.ToDouble(_en.Current); }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
_en.Dispose();
}
public bool MoveNext()
{
return _en.MoveNext();
}
public void Reset()
{
_en.Reset();
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_source.GetEnumerator());
}
IEnumerator<double> IEnumerable<double>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
var doubleList = new DoubleList(listOfObjects);
这绕着以这样的方式来改变什么费什么时候会发生什么。你会一直返回,但实际上使用这个列表将会更加昂贵。但是,如果只打算查看几个字段,或者只打算获取计数,然后通过它进行枚举,那么事实上,这不会完成一个完整的副本,可以使效率更高。
'List'表示'列表
你是如何获得这份名单的?数据来自哪里? – crush
动态是将类型强制转换为运行时的最佳方式 –