C# List<> 获取下一个元素或获取第一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/776725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List<> Get Next element or get the first
提问by The real napster
I want to get the next element in a list and if the list is at it's end I want the first element. So I just want it to circle in other words.
我想获取列表中的下一个元素,如果列表在它的末尾,我想要第一个元素。所以我只是想让它圈起来。
List<int> agents = taskdal.GetOfficeAgents(Branches.aarhusBranch);
if (lastAgentIDAarhus != -1)
{
int index = agents.IndexOf(lastAgentIDAarhus);
if (agents.Count > index + 1)
{
lastAgentIDAarhus = agents[index + 1];
}
else
{
lastAgentIDAarhus = agents[0];
}
}
else
{
lastAgentIDAarhus = agents[0];
}
I am fairly displeased with my own solution shown above, let me know if you have a better one :)
我对上面显示的自己的解决方案很不满意,如果您有更好的解决方案,请告诉我:)
采纳答案by Paul Alexander
lastAgentIDAarhus = agents[index == -1 ? 0 : index % agents.Count];
The use of the MOD operator %atuomatically chops the index to the range of possible indexes.
使用 MOD 运算符% 自动将索引切割为可能的索引范围。
The modulo operator is the compliment to the DIV (/) operator and returns the remainder of a division of two whole numbers. For example if you divide 9 by 6 the result is 1 with a remainder of 3. The MOD operator asks for the 3.
模运算符是对 DIV (/) 运算符的补充,并返回两个整数相除的余数。例如,如果将 9 除以 6,则结果为 1,余数为 3。 MOD 运算符要求为 3。
回答by Fredrik M?rk
Not a great difference, but at least some less code (at least in the editor) ;o)
差别不大,但至少少了一些代码(至少在编辑器中);o)
List<int> agents = taskdal.GetOfficeAgents(Branches.aarhusBranch);
if (lastAgentIDAarhus != -1)
{
int index = agents.IndexOf(lastAgentIDAarhus);
lastAgentIDAarhus = (agents.Count > index + 1 ? agents[index + 1] : agents[0]);
}
else
{
lastAgentIDAarhus = agents[0];
}
回答by Steve Willcock
As a slightly different take on this, here's an extension method you could use to make any IEnumerable 'circular'
作为对此略有不同的看法,这里有一个扩展方法,您可以使用它来制作任何 IEnumerable 'circular'
public static IEnumerable<T> AsCircularEnumerable<T>(this IEnumerable<T> enumerable)
{
var enumerator = enumerable.GetEnumerator();
if(!enumerator.MoveNext())
yield break;
while (true)
{
yield return enumerator.Current;
if(!enumerator.MoveNext())
enumerator = enumerable.GetEnumerator();
}
}
so you could use that like this
所以你可以像这样使用它
var agents = new List<int> {1, 2, 3, 4, 123, 234, 345, 546};
foreach(var i in agents.AsCircularEnumerable())
{
Console.WriteLine(i);
}
Which will just keep going... :)
这将继续下去...... :)
回答by Vinicius Gon?alves
Or simply:
或者干脆:
public static T NextOf<T>(this IList<T> list, T item)
{
var indexOf = list.IndexOf(item);
return list[indexOf == list.Count - 1 ? 0 : indexOf + 1];
}
Example:
例子:
List<string> names = new List<string>();
names.Add("jonh");
names.Add("mary");
string name = String.Empty;
name = names.NextOf(null); //name == jonh
name = names.NextOf("jonh"); //name == mary
name = names.NextOf("mary"); //name == jonh
回答by Big McLargeHuge
I like Vinicius's ideaof using an extension method. Unfortunately the code he posted will throw an exception. This is based on his, but it will not throw an exception and it is very straightforward and easy to read (IMHO):
我喜欢Vinicius使用扩展方法的想法。不幸的是,他发布的代码会抛出异常。这是基于他的,但它不会抛出异常,并且非常简单易读(恕我直言):
public static T Next<T>(this IList<T> list, T item)
{
var nextIndex = list.IndexOf(item) + 1;
if (nextIndex == list.Count)
{
return list[0];
}
return list[nextIndex];
}
It will return the first item in the list if the item passed in is not in the list, since list.IndexOf(item)
will return -1
in that case;
如果传入的项不在列表中,list.IndexOf(item)
它将返回列表中的第一项,因为-1
在这种情况下将返回;
回答by Riccardo Bassilichi
What do you think if we add some check to avoid common errors ?
如果我们添加一些检查来避免常见错误,您怎么看?
public static class ListExtensions
{
public static TType Next<TType>(this IList<TType> list, TType item)
{
if (list == null) return default(TType);
var itemIndex = list.IndexOf(item);
if (itemIndex < 0) return list.FirstOrDefault();
var nextIndex = itemIndex + 1;
return nextIndex >= list.Count
? list.FirstOrDefault()
: list[nextIndex];
}
}
回答by Diogo Fabricio
string line = lines[lines.FindIndex(x => x.Contains(item)) + 1];
字符串 line = lines[lines.FindIndex(x => x.Contains(item)) + 1];