c#中从object[]列表中检索int列表的最佳方法
本文关键字:列表 int 最佳 方法 检索 object 中从 | 更新日期: 2023-09-27 18:18:14
我试图从object[]
列表中检索id列表。下面是我的代码:
private static List<int> getReceivedIds(object[] objectList)
{
var received = new List<int>();
foreach (object[] b in objectList)
{
if (b != null)
{
received.Add(int.Parse((b[0].ToString())));
}
}
return received;
}
我正在寻找这个代码的性能优化的解决方案。
我把代码改成了:
private static List<int> getReceivedIds2(object[] objectList)
{
var received = new List<int>();
foreach (object[] b in objectList)
{
if (b != null)
{
received.Add((int)b[0]);
}
}
return received;
}
我还比较了LINQ查询和foreach
语句的性能,结果如下:性能测试结果
测试表明foreach
语句比LINQ语句快6倍。
谁能改进这段代码的性能?
下面是我的测试代码:class Program
{
static void Main(string[] args)
{
for (int test = 0; test < 100; test++)
{
object[] objectList = new object[1000];
Random rnd = new Random();
for (int i = 0; i < 1000; i++)
{
objectList[i] = new object[] { rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000), rnd.Next(1, 10000) };
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 1; i < 100000; i++)
{
getReceivedIds(objectList);
}
stopWatch.Stop();
var t1 = stopWatch.Elapsed.TotalMilliseconds;
stopWatch.Restart();
for (int i = 1; i < 100000; i++)
{
getReceivedIds2(objectList);
}
stopWatch.Stop();
var t2 = stopWatch.Elapsed.TotalMilliseconds;
Console.WriteLine(string.Format("LINQ: {0} - ForEach: {1}", t1, t2));
}
}
private static List<int> getReceivedIds(object[] objectList)
{
List<int> received = objectList.Cast<object[]>()
.Where(b => b != null)
.Select(b => (int)b[0]) // or Convert.ToInt32(b[0])
.ToList();
return received;
}
private static List<int> getReceivedIds2(object[] objectList)
{
var received = new List<int>();
foreach (object[] b in objectList)
{
if (b != null)
{
received.Add((int)b[0]);
}
}
return received;
}
}
如果object[]
中的第一项实际上是int
,则不需要解析它,可以对其进行强制转换。如果需要,可以使用以下LINQ查询:
List<int> received = objectList.Cast<object[]>()
.Where(b => b != null)
.Select(b => (int)b[0]) // or Convert.ToInt32(b[0])
.ToList();
try this:
int[] resultArray = Array.ConvertAll(inputArray, x => Convert.ToInt32(x));
注意:请确保值为整型。
参考:msdn链接ConvertAll()