如何选择列表中的项目C#? [英] How do I select an item in a list, C#?
本文介绍了如何选择列表中的项目C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个项目列表,我如何每次选择两个连续项目,例如(1和2)(2和3)(3和4)......等等?
我的尝试:
for(i = 0; i< ; = list.Count-1; i ++)
{
// var first = list(i);
// var second = list(i + 1);
}
解决方案
假设源实现IList< T> ;
或IReadOnlyList< T>
:
for ( int i = 0 ; i < list.Count - 1 ; i ++)
{
var first = list [i];
var second = list [i + 1 ];
}
如果你想使用LINQ:
foreach ( var 对 list.Zip(list.Skip( 1 ),(第一,第二)= > (第一,第二)))
{
var first = pair.first;
var second = pair.second;
}(使用新的C#7值元组语法 [ ^ ]。如果您使用的是较旧的编译器,或者使用较旧的框架,请使用匿名类型。 )的
I have a list of items, how can I select two consecutive items each time, for example (1 and 2) (2 and 3) (3 and 4)...etc?
What I have tried:
for (i = 0; i <= list.Count-1; i++) { //var first = list(i); //var second = list(i+1); }
解决方案
Assuming the source implementsIList<T>
orIReadOnlyList<T>
:
for (int i = 0; i < list.Count - 1; i++) { var first = list[i]; var second = list[i + 1]; }
If you want to use LINQ:
foreach (var pair in list.Zip(list.Skip(1), (first, second) => (first, second))) { var first = pair.first; var second = pair.second; }(Using the new C# 7 value tuple syntax[^]. If you're using an older compiler, or targeting an older framework, use an anonymous type instead.)
这篇关于如何选择列表中的项目C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文