在列表中连接列表而无需循环的最有效方法
public class Unicorn
{
public List<int> Numbers { get; set; }
}
unicorns.Add(new Unicorn() { Numbers = {1, 2, 3} } );
unicorns.Add(new Unicorn() { Numbers = {4, 5, 6} } );
unicorns.Add(new Unicorn() { Numbers = {7, 8, 9} } );
c# 4 中将所有列表连接成一个 {1, 2, 3, 4, 5, 6, 7, 8, 9 } 列表的最有效方法是什么?
最好(理想情况下;优先考虑;如果有选择的话)没有循环并且无 Linq。我对 .FindAll 进行了修改,但它没有挖掘它。
public class Unicorn
{
public List<int> Numbers { get; set; }
}
unicorns.Add(new Unicorn() { Numbers = {1, 2, 3} } );
unicorns.Add(new Unicorn() { Numbers = {4, 5, 6} } );
unicorns.Add(new Unicorn() { Numbers = {7, 8, 9} } );
What's the most efficient way in c# 4 to concatenate all the lists into one list of {1, 2, 3, 4, 5, 6, 7, 8, 9 } ?
Preferably (ideally; by preference; if one had a choice) no loops and Linq-less. I tinkered around with .FindAll, but it's not digging it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果没有测量,从性能角度来看,这里唯一让我犹豫的是 .ToList
如果有大量数字,ToList 可能会重复地重新分配其支持数组。为了避免这种行为,您必须了解预期有多少个数字。
Without measuring, the only thing in here that gives me pause from a performance perspective is the .ToList
If there are a TON of numbers, it's possible that ToList may repeatedly re-allocate its backing array. In order to escape this behavior, you have to have some idea about how many Numbers to expect.
这是一个完全满足您要求的解决方案:无 Linq 和无循环 - 我很确定您不想使用此代码:
Here's a solution that fully meets your requirements: No Linq and no loop - I'm pretty sure you do not want to use this code though:
你的要求很不寻常,但我想你总是可以写:
ForEach( ) 可以说符合“LINQ-less”,因为它是
List
的真正成员,而不是IEnumerable
,它实际上早于 LINQ 本身。Your requirements are quite out of the ordinary, but I guess you can always write:
ForEach() arguably qualifies as "LINQ-less", since it's a genuine member of
List<T>
, not an extension method onIEnumerable<T>
, and it actually predates LINQ itself.使用 .NET 4.0 的 Zip 运算符:
如果您想概括这一点,请检查哪个具有更多元素并将其用作上面的“b”
Using .NET 4.0's Zip operator:
If you want to generalize this, check which has more elements and use that as the "b" above