如何从数组中查找字符串的索引(前三个字符)

时间:2013-08-05 06:25:22

标签: c# .net

我想找到一个字符串的索引,仅用于数组的前三个字符

我有一个月的数组

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };

如果我写

     int t_ciMonth=8;(AUGUST)
     int pos = Array.IndexOf(t_caMonth, arrayEnglishMonth[t_ciMonth - 1]);

但如果我只希望索引只有前三个字符,即AUG如何找到它?

6 个答案:

答案 0 :(得分:5)

arrayEnglishMonth.ToList().FindIndex(s => s.Substring(0,3) == "AUG");

答案 1 :(得分:3)

你有两个我能想到的选择:

  1. Linq只是看起来像这样:

    var index = arrayEnglishMonth.Select((v, i) => new { v, i })
                                 .Where(c => c.v.StartsWith("AUG"))
                                 .Select(c => c.i)
                                 .First();
    

    这将首先遍历现有数组,创建包含值和索引的可枚举匿名对象,其中Where中传递的谓词返回true,之后仅选择索引并从可枚举中获取第一个元素。

    Demo

  2. 使用Linq查找相应月份,然后使用IndexOf方法:

    var item = arrayEnglishMonth.First(c => c.StartsWith("AUG"));
    var index = Array.IndexOf(arrayEnglishMonth, item);
    

    Demo

答案 2 :(得分:2)

你可以用一点Linq来做到这一点:

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
string[] t_caMonth = { ... };
string search = arrayEnglishMonth[7].Substring(0, 3); // "AUG";
int pos = t_caMonth
    .Select((s, i) => new { s, i }).Dump()
    .Where(x => x.s == search)
    .Select(x => x.i)
    .DefaultIfEmpty(-1).First();

或更简单:

int pos = t_caMonth.TakeWhile(s => s != search).Count();

如果找不到匹配的元素,最后一个解决方案将返回t_caMonth.Length而不是-1

答案 3 :(得分:0)

如果t_caMonth有大写字母且其值只有3个字母,您可以使用:

 int pos = Array.IndexOf(t_caMonth, arrayEnglishMonth[t_ciMonth - 1]
     .Substring(0,3));

为了管理超过3个字符的大小写和值,您可以:

var pos = -1;
var sel = t_caMonth
    .Select((i, index) => new { index, i = i.ToUpper() })
    .Where(i => 
        i.i.Substring(0,3) == arrayEnglishMonth[t_ciMonth - 1].Substring(0, 3))
    .Select(i => i.index);
if (sel.Count() > 0)
    pos = sel.FirstOrDefault();

您还可以从List<string>数组创建t_caMonth

var pos2 = t_caMonth
    .ToList()
    .FindIndex(i => 
        i.ToUpper().Substring(0, 3) == 
            arrayEnglishMonth[t_ciMonth - 1].Substring(0, 3));

答案 4 :(得分:0)

这是实现这个目标的方法

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
var searcheditem = arrayEnglishMonth.FirstOrDefault(item => item.Substring(0, 3) == "AUG");
if(searcheditem != null)
var itemIndex = Array.IndexOf(arrayEnglishMonth, searcheditem);

但@wdavo答案更好

答案 5 :(得分:0)

尝试使用以下内容,我认为这是最快的 Array.FindIndex(strArray, s => s.StartsWith("AUG"));

干杯。