获取Array List的索引 [英] Get the index of Array List

查看:83
本文介绍了获取Array List的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我对C中的数组列表有疑问#



我有一个包含以下元素的数组:

- LQI请求

-0123456

-LQI请求

-456789

LQI请求

-6789

.....



现在我想做的就是找到LQI请求的字符串,然后得到它旁边的字符串,这是我到目前为止所尝试的:(全局变量中的索引)

Hi everyone, I have a question to Array List in C#

I have an Array with the following elements:
- LQI REquest
-0123456
-LQI Request
-456789
LQI Request
-6789
.....

Now all I want to do is, find the string with LQI Request, and then get the string next to it, that's what I've tried so far:(index in a global variable)

if(myString.Contains("LQI"))
                {
                    index= stored_data.IndexOf(myString);
                }
MessageBox.Show(index.ToString());
MessageBox.Show(stored_data[index+1].Tostring());





每次运行此代码时,索引保持不变。它应该是:0,2,4



请帮助



Everytime i run this code, the index stays the same. IT should be: 0,2,4

Please help

推荐答案

你必须使用这个重载 IndexOf 方法: List< t> .IndexOf Method(T,Int32) [ ^ ]。文档页面提供了解决您问题的示例代码。
You have to use this overload of the IndexOf method: List<t>.IndexOf Method (T, Int32)[^]. The documentation page provides sample code addressing your issue.


有几种方法可以解决这个问题。



你可以使用枚举器:



There are a couple of ways to go about this.

You could use an enumerator:

IEnumerator<string> enumerator = dStrings.GetEnumerator() as IEnumerator<string>;

            bool nextIsMyValue = false;

            while (enumerator.MoveNext())
            {
                if (nextIsMyValue)
                {
                    string myvalue = enumerator.Current;
                    nextIsMyValue = false;
                }
                else if (enumerator.Current.Contains("LQI"))
                    nextIsMyValue = true;
            }





或者你可以使用linq(我最喜欢的)



Or you could use linq (my favored)

// This just gets the indexes of the items you want
int[] indexes =
    dStrings.Select((dString, index) => new {dString, index})
        .Where(n => n.dString.Contains("LQI"))
        .Select(n => n.index+1).ToArray();





有一些很酷的方法可以使用linq获得序列中的下一个但这些例子更容易掌握。< br $> b $ b

希望有所帮助^ _ ^

Andy



There are some cool ways to get the next in the sequence using linq but these examples are easier to grasp.

Hope it help ^_^
Andy


这篇关于获取Array List的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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