在我的應用程序中,我有一個可能是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
動態是將類型強制轉換爲運行時的最佳方式 –