[英]Best way to retrieve a List of int from a list of object[] in c#
我正在尝试从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();
尝试这个:
int[] resultArray = Array.ConvertAll(inputArray, x => Convert.ToInt32(x));
注意:确保值为 int。
供参考: ConvertAll() 的 msdn 链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.