列表<>获取下一个元素或获取第一个 [英] List<> Get Next element or get the first

查看:64
本文介绍了列表<>获取下一个元素或获取第一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取列表中的下一个元素,如果列表在末尾,我想要第一个元素.所以我只想换个圆圈.

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 :)

推荐答案

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

使用MOD运算符将索引自动切为可能的索引范围.

The use of the MOD operator % atuomatically chops the index to the range of possible indexes.

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

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.

这篇关于列表&lt;&gt;获取下一个元素或获取第一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆