列表获取下一个元素或获取第一个元素

我想获取列表中的下一个元素,如果列表结束,我想要第一个元素。 所以我只想用它来换句话说。

List 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]; } 

我对上面显示的自己的解决方案感到非常不满,如果你有更好的解决方案,请告诉我:)

 lastAgentIDAarhus = agents[index == -1 ? 0 : index % agents.Count]; 

使用MOD运算符 atuomatically将索引切断到可能的索引范围。

模运算符是对DIV(/)运算符的补充,并返回两个整数的除法的余数。 例如,如果将9除以6,则结果为1,余数为3. MOD运算符要求3。

或者干脆:

 public static T NextOf(this IList list, T item) { var indexOf = list.IndexOf(item); return list[indexOf == list.Count - 1 ? 0 : indexOf + 1]; } 

例:

 List names = new List(); 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 

对此略有不同,这里有一个扩展方法,你可以使用它来制作任何IEnumerable’循环’

  public static IEnumerable AsCircularEnumerable(this IEnumerable enumerable) { var enumerator = enumerable.GetEnumerator(); if(!enumerator.MoveNext()) yield break; while (true) { yield return enumerator.Current; if(!enumerator.MoveNext()) enumerator = enumerable.GetEnumerator(); } } 

所以你可以这样使用它

  var agents = new List {1, 2, 3, 4, 123, 234, 345, 546}; foreach(var i in agents.AsCircularEnumerable()) { Console.WriteLine(i); } 

哪个会继续…… 🙂

我喜欢Vinicius使用扩展方法的想法 。 不幸的是,他发布的代码会引发exception。 这是基于他的,但它不会抛出exception,它非常简单易读(恕我直言):

 public static T Next(this IList list, T item) { var nextIndex = list.IndexOf(item) + 1; if (nextIndex == list.Count) { return list[0]; } return list[nextIndex]; } 

如果传入的项不在列表中,它将返回列表中的第一项,因为在这种情况下list.IndexOf(item)将返回-1 ;

没有太大的区别,但至少有一些代码(至少在编辑器中); o)

 List 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]; } 

如果我们添加一些检查以避免常见错误,您怎么看?

 public static class ListExtensions { public static TType Next(this IList 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]; } } 

string line = lines [lines.FindIndex(x => x.Contains(item))+ 1];